设计模式之一【抽象工厂模式】

91 阅读2分钟

抽象工厂模式

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

 

在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

 

简单的工厂模式是一个工厂创建跟这个工厂类型一致的对象。

抽象工厂可以看做是一个大工厂里面包含着其他小工厂  ,这个工厂可以创建不同类型的工厂 。 

 

举例子来说

现在我们需要一个工厂技能创建color对象,又能创建shape对象 ,color和shape这两个小工厂又能分别取创建自己同种类型不同属性的对象 ,比如red 、blue ,Squal  、 Rectangle!

 

分别创建color和shape接口

 

Color 接口

public interface Color {

     public  void test();
}

 

Shape 接口

public interface Shape {
    void test();
}

 

实现不同接口的对象

BuleColor.java

public class BuleColor implements  Color {

    @Override
    public void test() {
        System.out.println("bule");
    }
}

RedColor.java

public class RedColor implements Color {

@Override

public void test() {

System.out.println("red");

}

}

 

Rectangle .java

public class Rectangle implements Shape {
    @Override
    public void test() {
        System.out.println("Rectangle");
    }
}

Squal .java

public class Squal implements Shape {
    @Override
    public void test() {
        System.out.println("squal");
    }
}

 

创建一个抽象工厂 

提供两个接口,分别用来获取color和shape工厂,让这2个工厂去创建对象。

public interface AbstractFactoryTest {

    Color getColor(String color);
    Shape getShape(String shape);
}

实现类

ColorFactory.java

public class ColorFactory implements AbstractFactoryTest {


    @Override
    public Color getColor(String color) {


        if(color == null){
            return null;
        }
        if(color.equalsIgnoreCase("RedColor")){
            return new RedColor();
        } else if(color.equalsIgnoreCase("BuleColor")){
            return new BuleColor();
        }


        return null;
    }

    @Override
    public Shape getShape(String shape) {


        return null;
    }
}

 

ShapeFactory .java

public class ShapeFactory  implements AbstractFactoryTest {


    @Override
    public Color getColor(String color) {
        return null;
    }

    @Override
    public Shape getShape(String shape) {


        if(shape == null){
            return null;
        }
        if(shape.equalsIgnoreCase("Squal")){
            return new Squal();
        } else if(shape.equalsIgnoreCase("Rectangle")){
            return new Rectangle();
        }

        return null;
    }
}

 

 

获取对象

public static void main(String args []){

    //获取颜色工厂对象
    AbstractFactoryTest colorShapeFactory = new ColorFactory();

    Color color = colorShapeFactory.getColor("BuleColor");
    color.test();
    color = colorShapeFactory.getColor("RedColor");
    color.test();

    //获取形状工厂对象
    AbstractFactoryTest shapeFactory = new ShapeFactory();

    Shape shape = shapeFactory.getShape("Squal");
    shape.test();

    //Rectangle
    shape = shapeFactory.getShape("Rectangle");
    shape.test();


}

 

结果