抽象工厂模式建立父类的工厂,通过父类创建子类工厂,通过子类工厂创建对象。
本例中有两个接口Shape和Color,通过两个子工厂,ShapeFactory和ColorFactory,父类工厂FactoryProducer生成相应的子类工厂。
public interface Shape {
void draw();
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public interface Color {
void fill();
}
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
public class Red implements Color {
@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("Inside Green::fill() method.");
}
}
public abstract class AbstractFactory { abstract Color getColor(String color); abstract Shape getShape(String shapeType); }
public class ColorFactory extends AbstractFactory { @Override Color getColor(String color) { if (color == null) return null; if (color.equalsIgnoreCase("RED")) return new Red(); else if (color.equalsIgnoreCase("GREEN")) return new Green(); else if (color.equalsIgnoreCase("BLUE")) return new Blue(); return null; } @Override Shape getShape(String shapeType) { return null; } }
public class ShapeFactory extends AbstractFactory { @Override Color getColor(String color) { return null; } @Override public Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.equalsIgnoreCase("CIRCLE")) return new Circle(); else if (shapeType.equalsIgnoreCase("RECTANGLE")) return new Rectangle(); else if (shapeType.equalsIgnoreCase("SQUARE")) return new Square(); return null; } }
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; } }
public class Demo { public static void main(String[] args) { AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE"); Shape shape1 = shapeFactory.getShape("RECTANGLE"); shape1.draw(); Shape shape2 = shapeFactory.getShape("CIRCLE"); shape2.draw(); AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR"); Color red = colorFactory.getColor("RED"); red.fill(); } }
输出:Inside Rectangle::draw() method. Inside Circle::draw() method. Inside Red::fill() method.