1、问题描述
小明家有两个工厂,一个用于生产圆形积木,一个用于生产方形积木,请你帮他设计一个积木工厂系统,记录积木生产的信息。
输入案例
3
Circle 1
Square 2
Circle 1
2、工厂模式
将产品的创建过程封装在⼀个⼯⼚类中,把创建对象的流程集中在这个⼯⼚类⾥⾯
看图
3、解决方案
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{@Overridepublic void draw() {System.out.println("Circle Block");}
}
class SquareBlocks implements Blocks{@Overridepublic 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();}
}