设计模式---抽象工厂

来源:互联网 发布:l36h刷机软件 编辑:程序博客网 时间:2024/06/15 05:48
建立两个接口
public interface Shape {    void draw();}
public interface Color {    void fill();}
/////////////////////////////////////////////////////////////////////////////////

分别实现上面的两个接口
public class Square implements Shape {    @Override    public void draw() {        System.out.println("画个正方形");    }}
public class Circle implements Shape {    @Override    public void draw() {        System.out.println("画个圆");    }}
public class Red implements Color{    @Override    public void fill() {        System.out.println("图成红色");    }}
public class Green implements Color{    @Override    public void fill() {        System.out.println("图成绿色");    }}
//////////////////////////////////////////////////////////////////////////////

设置一个抽象工厂
public abstract class AbstractFactory {    abstract Color getColor(String color);    abstract Shape getShape(String shape);}
//////////////////////////////////////////////////////////////////////////

public class FactoryProducer {    public static AbstractFactory getFactory(String choies) {        if (choies.equalsIgnoreCase("shape")) {            return new ShapeFactory();        }        else if (choies.equalsIgnoreCase("color")) {            return new ColorFactory();        }        return null;    }}
/////////////////////////////////////////////////////////////////////////

继承抽象工厂,重写里面的方法,根据参数便于创建合适的实例
public class ShapeFactory extends AbstractFactory {    @Override    Shape getShape(String shape) {        if (shape.equalsIgnoreCase("square")) {            return new Square();        }        else if(shape.equalsIgnoreCase("circle")) {            return new Circle();        }        return null;    }    @Override    Color getColor(String color) {        return null;    }}
public class ColorFactory extends AbstractFactory {    @Override    Color getColor(String color) {        if (color.equalsIgnoreCase("red")) {            return new Red();        }        else if (color.equalsIgnoreCase("green")) {            return new Green();        }        return null;    }    @Override    Shape getShape(String shape) {        return null;    }}
//////////////////////////
public class Test {    public static void main(String[] args) {        AbstractFactory shapeFactory = FactoryProducer.getFactory("shape");        Shape shape1 = shapeFactory.getShape("square");        Shape shape2 = shapeFactory.getShape("circle");        shape1.draw();        shape2.draw();        AbstractFactory colorFactory = FactoryProducer.getFactory("color");        Color color1 = colorFactory.getColor("red");        Color color2 = colorFactory.getColor("green");        color1.fill();        color2.fill();    }}