设计模式代码实战-工厂模式

1、问题描述

小明家有两个工厂,一个用于生产圆形积木,一个用于生产方形积木,请你帮他设计一个积木工厂系统,记录积木生产的信息。
输入案例

3

Circle 1

Square 2

Circle 1

2、工厂模式

将产品的创建过程封装 在⼀个**⼯⼚类** 中,把创建对象的流程 集中在这个**⼯⼚类** ⾥⾯

看图

3、解决方案

java 复制代码
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int number=sc.nextInt();
        sc.nextLine();
        for(int i=0;i<number;i++){

            String s=sc.nextLine();

            String[] arr=s.split(" ");
            int count=Integer.parseInt(arr[1]);

            if(arr[0].equals("Circle")){
                Factory factory=new CircleFactory();
                Blocks circleInstance=factory.createBlocks();
                for(int j=0;j<count;j++){
                    circleInstance.draw();
                }

            }else if(arr[0].equals("Square")){
                Factory factory=new SquareFactory();
                Blocks squareInstance=factory.createBlocks();
                for(int j=0;j<count;j++) {
                    squareInstance.draw();
                }
            }

        }
    }
}

interface Blocks{
    void draw();
}
class CircleBlocks implements Blocks{

    @Override
    public void draw() {
        System.out.println("Circle Block");
    }
}
class SquareBlocks implements Blocks{

    @Override
    public void draw() {
        System.out.println("Square Block");
    }
}

interface Factory{
    Blocks createBlocks();
}

class CircleFactory implements Factory{
    public CircleBlocks createBlocks(){
        return new CircleBlocks();
    }
}

class SquareFactory implements Factory{
    public SquareBlocks createBlocks(){
        return new SquareBlocks();
    }
}
相关推荐
willow3 天前
Axios由浅入深
设计模式·axios
七月丶5 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞5 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼5 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟6 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder6 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室6 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦7 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo10 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式