抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
Class Diagram
Implementation
接口及其实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public interface Shape { void draw(); }
public interface Color { void fill(); }
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
public class Green implements Color {
public void fill() { System.out.println("Inside Green::fill() method."); } }
public class Red implements Color { @Override public void fill() { System.out.println("Inside Red::fill() method."); } }
|
抽象工厂
1 2 3 4
| public abstract class AbstractFactory { public abstract Color getColor(String color); public abstract Shape getShape(String shape); }
|
实例工厂类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class ColorFactory extends AbstractFactory {
@Override public Shape getShape(String shapeType){ return null; }
@Override public Color getColor(String color) { if(color == null){ return null; } if(color.equalsIgnoreCase("RED")){ return new Red(); } else if(color.equalsIgnoreCase("GREEN")){ return new Green(); } return null; } }
public class ShapeFactory extends AbstractFactory { @Override public Color getColor(String color) { return null; }
@Override public Shape getShape(String shapeType) { if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
|
工厂创建类
1 2 3 4 5 6 7 8 9 10
| public class FactoryProducer { public static AbstractFactory getFactory(String choice){ if(choice.equalsIgnoreCase("SHAPE")){ return new ShapeFactory(); } else if(choice.equalsIgnoreCase("COLOR")){ return new ColorFactory(); } return null; } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class AbstractFactoryTest { @Test public void test() throws Exception { AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
Color color1 = colorFactory.getColor("RED");
color1.fill();
Color color2 = colorFactory.getColor("Green");
color2.fill(); } }
|
Example