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

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();
    }
}
相关推荐
Zane19945 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫6 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19946 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19948 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..8 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1508 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)9 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki9 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅669 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa9 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio