工厂模式

2019-04-10  本文已影响0人  意大利大炮

简介

介绍

优缺点

使用场景

实现

我们将创建一个 Shape 接口和实现 Shape 接口的实体类。下一步是定义工厂类 ShapeFactory。
FactoryPatternDemo,我们的演示类使用 ShapeFactory 来获取 Shape 对象。它将向 ShapeFactory 传递信息(CIRCLE / RECTANGLE / SQUARE),以便获取它所需对象的类型。

factory_pattern_uml_diagram.jpg
  1. 创建一个接口
public interface Shape {
    void draw();
}
  1. 三个Shape接口的实现类
public class Circle implements Shape {
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}
public class Rectangle implements Shape {
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}
public class Square implements Shape {
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}
  1. 一个枚举,用于对应三个实现类的类型
public enum ShapeTypeEnum {
    CIRCLE,
    RECTANGLE,
    SQUARE
}
  1. 创建一个工厂,生成基于给定信息的实体类的对象
public class ShapeFactory {

    public Shape getShape(ShapeTypeEnum shapeTypeEnum) {
        if (shapeTypeEnum == null) {
            return null;
        }

        switch (shapeTypeEnum) {
            case CIRCLE: return new Circle();
            case SQUARE: return new Square();
            case RECTANGLE: return new Rectangle();
        }
        return null;
    }
}
  1. 通过工厂类生成不同实体类的对象
public class FactoryPatternDemo {
    @Test
    public void test() {
        ShapeFactory shapeFactory = new ShapeFactory();
        shapeFactory.getShape(ShapeTypeEnum.CIRCLE).draw();
        shapeFactory.getShape(ShapeTypeEnum.RECTANGLE).draw();
        shapeFactory.getShape(ShapeTypeEnum.SQUARE).draw();
    }
}
  1. 输出结果:
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
上一篇 下一篇

猜你喜欢

热点阅读