抽象工厂模式
工厂模式是用来创建对象的工厂,那么抽象工厂模式就是创建工厂的工厂。
类图
代码实现
- 定义
Color
接口
package com.pattern.abstractfactory;
public interface Color {
public void fill();
}
- 实现三个具体的类
package com.pattern.abstractfactory;
public class Red implements Color {
@Override
public void fill() {
// TODO Auto-generated method stub
System.out.println("Red is filled.");
}
}
package com.pattern.abstractfactory;
public class Green implements Color {
@Override
public void fill() {
// TODO Auto-generated method stub
System.out.println("Green is filled.");
}
}
package com.pattern.abstractfactory;
public class Blue implements Color {
@Override
public void fill() {
// TODO Auto-generated method stub
System.out.println("Blue is filled.");
}
}
- 定义具体的
Color
工厂
package com.pattern.abstractfactory;
import com.pattern.factory.Shape;
public class ColorFactory extends AbstractFactory {
@Override
public Color getColor(String color) {
// TODO Auto-generated method stub
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
public Shape getShape(String shape) {
// TODO Auto-generated method stub
return null;
}
}
- 定义抽象工厂接口
package com.pattern.abstractfactory;
import com.pattern.factory.*;
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape);
}
- 定义工厂产生器
package com.pattern.abstractfactory;
public class FactoryProducer {
public static AbstractFactory getFactory(String choice) {
if (choice.equalsIgnoreCase("Color")) {
return new ColorFactory();
} else if (choice.equalsIgnoreCase("Shape")) {
return new ShapeFactory();
}
return null;
}
}
- 主类
package com.pattern.abstractfactory;
import com.pattern.factory.Shape;
public class FactoryDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractFactory shapeFactory = FactoryProducer.getFactory("shape");
Shape circle = shapeFactory.getShape("circle");
circle.draw();
Shape square = shapeFactory.getShape("square");
square.draw();
Shape rectangle = shapeFactory.getShape("rectangle");
rectangle.draw();
AbstractFactory colorFactory = FactoryProducer.getFactory("color");
Color red = colorFactory.getColor("red");
red.fill();
Color green = colorFactory.getColor("green");
green.fill();
Color blue = colorFactory.getColor("blue");
blue.fill();
}
}
总结
- 抽象工厂设计模式是产生工厂的工厂,其类似于python中的
元类
,用于生产类的类。
参考
[1] 易百教程