工厂模式

接口:

public interface Shape {
 void draw();
}

实体类:

public class Rectangle implements Shape {

    @Override
    public void draw() {
        System.out.println("Inside Rectangle:draw() method.");
    }

}

public class Square implements Shape {

    @Override
    public void draw() {
        System.out.println("Inside Square:draw() method.");
    }

}

public class Circle implements Shape {

    @Override
    public void draw() {
        System.out.println("Inside Circle:draw() method.");
    }

}

创建一个工厂,生成基于给定信息的实体类的对象。
ShapeFactory.java

public class ShapeFactory {

    public Shape getShape(String shapeType){
        switch (shapeType) {
        case "CIRCLE":
            return new Circle();

        case "RECTANGLE":
            return new Rectangle();
        case "SQUARE":
            return new Square();
        }
        return null;
    }
}

使用该工厂,通过传递类型信息来获取实体类的对象。
FactoryPatternDemo.java

public class FactoryPatternDemo {
     public static void main(String[] args) {
          ShapeFactory shapeFactory = new ShapeFactory();

          //获取 Circle 的对象,并调用它的 draw 方法
          Shape shape1 = shapeFactory.getShape("CIRCLE");

          //调用 Circle 的 draw 方法
          shape1.draw();

          //获取 Rectangle 的对象,并调用它的 draw 方法
          Shape shape2 = shapeFactory.getShape("RECTANGLE");

          //调用 Rectangle 的 draw 方法
          shape2.draw();

          //获取 Square 的对象,并调用它的 draw 方法
          Shape shape3 = shapeFactory.getShape("SQUARE");

          //调用 Square 的 draw 方法
          shape3.draw();
       }
}

验证输出。
Inside Circle:draw() method.
Inside Rectangle:draw() method.
Inside Square:draw() method.

posted @ 2017-09-04 09:46  webzom  阅读(77)  评论(0)    收藏  举报