抽象工厂模式是在工厂模式上的进一步扩展: 工厂模式可以通过传递给工厂类一个字符串不同创建不同的实例 抽象工厂是在此基础上在加一层通过工厂来创建工厂
代码如下:
color.java 接口 shape.java 接口 他们的实现类
package testDesignDemo.abstractfactory;
public interface Color {
public String getColor();
}
package testDesignDemo.abstractfactory;
public class ColorBlue implements Color {
@Override
public String getColor() {
return "blue";
}
}
package testDesignDemo.abstractfactory;
public interface Shape {
public String getShape();
}
package testDesignDemo.abstractfactory;
public class Roundness implements Shape {
@Override
public String getShape() {
return "圆形";
}
}
抽象工厂:
package testDesignDemo.abstractfactory;
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape);
}
各自的实现工厂:
package testDesignDemo.abstractfactory;
public class ShapeFactory extends AbstractFactory{
public Shape getShape(String shape){
if(shape.equalsIgnoreCase("Square")){
return new Square();
}
if(shape.equalsIgnoreCase("Roundness")){
return new Roundness();
}
return null;
}
@Override
public Color getColor(String color) {
// TODO Auto-generated method stub
return null;
}
}
package testDesignDemo.abstractfactory;
public class ColorFactory extends AbstractFactory {
public Color getColor(String color){
if(color.equalsIgnoreCase("red")){
return new ColorRed();
}
if(color.equalsIgnoreCase("blue")){
return new ColorBlue();
}
return null;
}
@Override
public Shape getShape(String shape) {
// TODO Auto-generated method stub
return null;
}
}
最后是产品工厂
package testDesignDemo.abstractfactory;
public class FactoryProducer {
public static AbstractFactory getProducer(String producer){
if(producer.equalsIgnoreCase("red")){
return new ColorFactory();
}
return null;
}
}
然后你可以通过产品工厂来创建 不同的颜色和形状你也可以同时创建两者(需要加一个工厂)