本文共 2035 字,大约阅读时间需要 6 分钟。
简单工厂模式又叫静态工厂方法,由一个工厂对象决定创建某一种对象类的实例,这种类型的设计模式属于创建型模式,在简单工厂模式中,可以根据参数的不同返回不同类的实例,简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
简单工厂模式目的是定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到工厂方法中进行,主要解决接口选择的问题,让其子类实现工厂接口,返回的也是一个抽象的产品。
Factory
: 工厂角色,工厂角色负责实现创建所有实例的内部逻辑。Product
: 抽象产品角色,抽象产品角色是所创建的所有对象的父类,负责描述所有实例所共有的公共接口。ConcreteProduct
: 具体产品角色,具体产品角色是创建目标,所有创建的对象都充当这个角色的某个具体类的实例。class Shape { // 基类 say(){ console.log(this.name); }}class Rectangle extends Shape{ // 长方形产品 constructor(){ super(); this.name = "Rectangle"; }}class Square extends Shape{ // 正方形产品 constructor(){ super(); this.name = "Square"; }}class Circle extends Shape{ // 圆形产品 constructor(){ super(); this.name = "Circle"; }}class ShapeFactory{ // 产品工厂 getShape(shape) { switch (shape.toLowerCase()) { case "rectangle": return new Rectangle(); case "square": return new Square(); case "circle": return new Circle(); default: throw new Error("参数错误"); } }}var shapeFactory = new ShapeFactory();var rectangle = shapeFactory.getShape("rectangle");rectangle.say(); // Rectanglevar square = shapeFactory.getShape("square");square.say(); // Squarevar circle = shapeFactory.getShape("circle");circle.say(); // Circle
https://github.com/WindrunnerMax/EveryDay
https://juejin.im/post/6844903653774458888https://www.runoob.com/design-pattern/factory-pattern.htmlhttps://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html
转载地址:http://btckz.baihongyu.com/