• (Head First)设计模式基础


    一,工厂模式

    所以设计模式的一个重要目就是将系统中经常变化的部分从相对固定的部分抽离出来,减少代码变更可能对系统造成的影响。即开闭原则。

    All factory patterns encapsulate object creation. The Factory Method Pattern encapsulates
    object creation by letting subclasses decide what objects to create.
     
    工厂方法其实可以看做一个框架(半成品),编写一个实现工厂方法的子类,便可开始工作。
    简单工厂可以封装对象创建细节,但是没有工厂方法那样强的灵活性,适应性。因为简单工厂不能根据不同的需求对应的调整对象创建细节。

    Q: I’m still a bit confused about the difference
    between Simple Factory and Factory Method. They
    look very similar, except that in Factory Method, the
    class that returns the pizza is a subclass. Can you
    explain?
    A: You’re right that the subclasses do look a lot
    like Simple Factory, however think of Simple Factory
    as a one shot deal, while with Factory Method you are
    creating a framework that let’s the subclasses decide
    which implementation will be used. For example, the
    orderPizza() method in the Factory Method provides a
    general framework for creating pizzas that relies on a
    factory method to actually create the concrete classes
    that go into making a pizza. By subclassing the
    PizzaStore class, you decide what concrete products
    go into making the pizza that orderPizza() returns.
    Compare that with SimpleFactory, which gives you a
    way to encapsulate object creation, but doesn’t give
    you the flexibility of the Factory Method because there
    is no way to vary the products you’re creating.

    抽象工厂模式与工厂方法模式

    抽象工厂模式的具体工厂在创建产品时使用了工厂方法。抽象工厂只是用来创建产品。

    工厂方法模式通常会把消费产品的方法直接写在抽象建造者中。

    HeadFirst: Abstract Factory, I heard that you often use
    factory methods to implement your concrete factories?
    Abstract Factory: Yes, I’ll admit it, my concrete
    factories often implement a factory method to create
    their products. In my case, they are used purely to create
    products...
    Factory Method: ...while in my case I usually
    implement code in the abstract creator that makes use of
    the concrete types the subclasses create.

    工厂方法的焦点在于声明了一个抽象方法,属于方法级别的模式,适合管理一个产品。抽象工厂的核心在于声明一套相关产品创建的接口,属于类级别的模式,适合管理一套产品。

  • 相关阅读:
    工作总结系列【前端入职前准备事项清单】
    git系列【如何重新设置和修改git账号和密码】
    echarts系列 【vue+echarts实现折线面积图、饼图、柱状图】
    vscode系列【vscode常用插件大全】
    vue系列【兄弟组件之间实现传值】
    vue系列【vue使用ref获取高度为underfind和resetFields()重置功能无效】
    Konva系列【使用Konva实现2d效果】
    three.js系列【3D之Three.js实现三维场景】
    canvas系列【vue和原生js中canvas图形的绘制】
    第二节软件测试基本概念及分类
  • 原文地址:https://www.cnblogs.com/wllhq/p/13627104.html
Copyright © 2020-2023  润新知