b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

抽象工厂模式 java_抽象工厂模式_抽象工厂模式的实现(2)

电脑杂谈  发布时间:2017-01-17 08:14:06  来源:网络整理

创建一个厂发电机/生产类传递一个信息,如形状或打印机拿到工厂

class FactoryProducer {
   public static AbstractFactory getFactory(String choice){
      if(choice.equalsIgnoreCase("SHAPE")){
         return new ShapeFactory();
      } else if(choice.equalsIgnoreCase("Printer")){
         return new PrinterFactory();
      }
      return null;
   }
}

下面的代码演示了如何使用抽象工厂模式

public class Main {
   public static void main(String[] args) {

      //get shape factory
      AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");

      //get an object of Shape Circle
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Shape Circle
      shape1.draw();

      //get an object of Shape Rectangle
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Shape Rectangle
      shape2.draw();
      
      //get an object of Shape Square 
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of Shape Square
      shape3.draw();

      //get printer factory
      AbstractFactory printerFactory = FactoryProducer.getFactory("printer");

    Printer printer1 = printerFactory.getPrinter("Paper");
    printer1.print();
    Printer printer2 = printerFactory.getPrinter("Web");
    printer2.print();
    Printer printer3 = printerFactory.getPrinter("Screen");
    printer3.print();
   }
}


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-26867-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 宇文化及
      宇文化及

      尽快在南海建立军事设施

    热点图片
    拼命载入中...