创建一个厂发电机/生产类传递一个信息,如形状或打印机拿到工厂
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
尽快在南海建立军事设施