类图对工厂模式的形状实例进行扩展,增加颜色填充功能。
- 形状和颜色接口
public interface Color {
void fill();
}
------------------------------------------------------
public interface Shape {
void draw();
}
- 颜色实现类(形状的实现类上一篇有)
public class Blue implements Color{
@Override
public void fill() {
System.out.println("fill Blue color!");
}
}
------------------------------------------------------
public class Red implements Color{
@Override
public void fill() {
System.out.println("fill Red color!");
}
}
------------------------------------------------------
public class Yellow implements Color{
@Override
public void fill() {
System.out.println("fill Yellow color!");
}
}
- 为 Color 和 Shape 对象创建抽象类来获取工厂
public interface AbstractFactory {
Color getColor(String color);
Shape getShape(String shape);
}
- 创建扩展了 AbstractFactory 的工厂类,基于给定的信息生成实体类的对象
public class ColorFactory implements AbstractFactory{
@Override
public Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
} else if(color.equalsIgnoreCase("YELLOW")){
return new Yellow();
} else if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
@Override
public Shape getShape(String shape) {
return null;
}
}
----------------------------------------------------------------------------------
public class ShapeFactory implements AbstractFactory{
@Override
public Color getColor(String color) {
return null;
}
@Override
public Shape getShape(String shape) {
if(shape == null){
return null;
}
if(shape.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shape.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shape.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;
}
}
- 使用 FactoryProducer 来获取 AbstractFactory,通过传递类型信息来获取实体类的对象
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
AbstractFactory colorFatory = FactoryProducer.getFactory("color");
Color red = colorFatory.getColor("red");
red.fill();
Color yellow = colorFatory.getColor("yellow");
yellow.fill();
Color blue = colorFatory.getColor("blue");
blue.fill();
AbstractFactory shapeFactory = FactoryProducer.getFactory("shape");
Shape rectangle = shapeFactory.getShape("rectangle");
rectangle.draw();
Shape circle = shapeFactory.getShape("circle");
circle.draw();
Shape square = shapeFactory.getShape("square");
square.draw();
}
}
- 输出结果:
fill Red color!
fill Yellow color!
fill Blue color!
Draw Rectangle!
Draw Circle!
Draw Square!
网友评论