任何可以产生对象的方法或者类都可以叫做工厂。
抽象工厂:一个超级工厂创建其他工厂
上图展示:
代码实现:
为形状创建一个接口
package com.dl.pattern.abstractFactory;
public interface Shape {
public void drow();
}
创建实体类
package com.dl.pattern.abstractFactory;
public class Circle implements Shape {
@Override
public void drow() {
System.out.println("画了一个圆");
}
}
package com.dl.pattern.abstractFactory;
public class Rectangle implements Shape {
@Override
public void drow() {
System.out.println("画了一个长方形");
}
}
package com.dl.pattern.abstractFactory;
public class Square implements Shape{
@Override
public void drow() {
System.out.println("画了一个正方形");
}
}
创建颜色实体类
package com.dl.pattern.abstractFactory;
public interface Color {
public void fill();
}
package com.dl.pattern.abstractFactory;
public class Blue implements Color {
@Override
public void fill() {
System.out.println("填满蓝色");
}
}
package com.dl.pattern.abstractFactory;
public class Green implements Color {
@Override
public void fill() {
System.out.println("填满绿色");
}
}
package com.dl.pattern.abstractFactory;
public class Red implements Color {
@Override
public void fill() {
System.out.println("填满红色");
}
}
为Color 和 Shape 对象创建抽象类来获取工厂。
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape);
}
创建扩展了 AbstractFactory 的工厂类,基于给定的信息生成实体类的对象。
package com.dl.pattern.abstractFactory;
public class ColorFactory extends AbstractFactory{
@Override
public Color getColor(String color) {
if (color==null){
return null;
}
if (color.equalsIgnoreCase("red")){
return new Red();
}else if (color.equalsIgnoreCase("blue")){
return new Blue();
}else if (color.equalsIgnoreCase("green")){
return new Green();
}
return null;
}
@Override
public Shape getShape(String shape) {
return null;
}
}
package com.dl.pattern.abstractFactory;
/**
* 创建一个工厂创造器,通过传递形状和颜色来获取工厂
*/
public class FactoryProduct {
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 FactoryProduct {
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 AbstractFactoryPatternTest {
public static void main(String[] args) {
//获取形状工厂
AbstractFactory shareFactory = FactoryProduct.getFactory("shape");
//获取形状为Circle的对象
Shape circle = shareFactory.getShape("circle");
circle.drow();
Shape square = shareFactory.getShape("square");
square.drow();
Shape rectangle = shareFactory.getShape("rectangle");
rectangle.drow();
AbstractFactory colorFactory = FactoryProduct.getFactory("color");
Color red = colorFactory.getColor("red");
red.fill();
Color blue = colorFactory.getColor("blue");
blue.fill();
Color green = colorFactory.getColor("green");
green.fill();
}
}