【设计模式之工厂方法模式——积木工厂】

题目描述
小明家有两个工厂,一个用于生产圆形积木,一个用于生产方形积木,请你帮他设计一个积木工厂系统,记录积木生产的信息

输入描述
输入的第一行是一个整数 N(1 ≤ N ≤ 100),表示生产的次数。
接下来的 N 行,每行输入一个字符串和一个整数,字符串表示积木的类型。积木类型分为 “Circle” 和 “Square” 两种。整数表示该积木生产的数量

输出描述
对于每个积木,输出一行字符串表示该积木的信息。

输入示例
3
Circle 1
Square 2
Circle 1

输出示例
Circle Block
Square Block
Square Block
Circle Block

import java.util.Scanner;

public class Main{
 public static void main (String[] args) {
 Scanner sc=new Scanner(System.in);
   int n=sc.nextInt();
  
   while(n>0){ //这里的n是行数,即生产的次数。
        String name=sc.next();//什么积木,即积木类型。
        int num=sc.nextInt();//这里的num是该积木的生产数量
        for(int i=0;i<num;i++){
            if(name.equals("Circle")){
               ShapeFactory shapeFactory = new CircleFactory();
               shapeFactory.createFactory();
            }else{
                 ShapeFactory shapeFactory = new SquareFactory();
                 shapeFactory.createFactory();
                 }
        }
           n--;
   }
}
}

interface Shape{//抽象产品,定义了工厂的积木  生产的功能
    void produce();
}

class Circle implements Shape{//具体产品
    @Override
    public void produce(){
        System.out.println("Circle Block");
    }
}


class Square implements Shape{
    @Override
    public void produce(){
        System.out.println("Square Block");
    }
}



interface ShapeFactory{//抽象工厂,用于创建产品对象
    Shape createFactory();
}


class CircleFactory implements ShapeFactory{//具体工厂,创建了什么样子的工厂。返回具体的产品实例
    @Override
    public Shape createFactory(){
        System.out.println("Circle Block");
        return new Circle();
    }
}


class SquareFactory implements ShapeFactory{
    @Override
    public Shape createFactory(){
        System.out.println("Square Block");
        return new Square();
    }
}

ps: 题目来自卡哥卡码网

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值