[Design Pattern] Factory Pattern 简单案例

Factory Pattern , 即工厂模式,用于创建对象的场景,属于创建类的设计模式 。

下面是一个工厂模式案例。 Shape 作为接口, Circle, Square, Rectangle 作为具体类实现了 Shape 接口。 ShapeFactory 封装了创建各个 Shape 的方式,隐藏了 new 命令。FactoryPatternDemo 用于演示工厂模式。

具体代码:

Shape 接口定义

public interface Shape {

    public void draw();
}

Circle / Rectangle / Square 三个具体类的实现,实现 Shape 接口

public class Circle implements Shape {

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

    @Override
    public void draw() {

        System.out.println("Rectangle - draw");
    }
}
public class Square implements Shape{

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

ShapeFactory 工厂类,根据传入的参数,即Shape 的具体名称,来创建返回对象

public class ShapeFactory {

    public static Shape getShape(String shapeName){
        Shape shape = null;
        if ("Circle".equals(shapeName)){
            shape = new Circle();
        }
        else if ("Rectangle".equals(shapeName)){
            shape = new Rectangle();
        }
        else if ("Square".equals(shapeName)){
            shape = new Square();
        }
        
        return shape;
    }
}

使用演示

public class FactoryPatternDemo {

    public static void main(){
        Shape circle = ShapeFactory.getShape("Circle");
        circle.draw();
        
        Shape rectangle = ShapeFactory.getShape("Rectangle");
        rectangle.draw();
        
        Shape square = ShapeFactory.getShape("Square");
        square.draw();
    }
}

个人理解

本案例的优点有:

1. FactoryPatternDemo 作为工厂模式的使用方,使用 Shape 接口来声明变量,避免和具体实现耦合,这是针对接口编程的体现。

2. Shape 对象的创建(new) 都被封装在 ShapeFactory 里面,FactoryPatternDemo 无需使用 new 命令即可获得新对象。这有利于后期拓展维护。

拓展时,涉及的变动文件:

例如,在系统中需要增加一个三角形对象 triangle 。

1. 增加一个文件,实现 Trianlge 类, 使其实现 Shape 接口,实现 draw() 方法

2. 在 ShapeFactory::getShape() 方法中增加支持 Triangle 的调用。

这样调用方即可使用新增的 Triangle 对象。

参考资料 

Design Pattern - Factory Pattern

原文地址:https://www.cnblogs.com/TonyYPZhang/p/5514536.html