Motivation for Simple Factory and Factory Method Pattern

后端 未结 6 907
猫巷女王i
猫巷女王i 2020-12-16 20:22

I know there are a lot of questions out there about differences of different factory patterns, but the answers are so different and confusing. The books that i read use uncl

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 20:53

    You are seeing examples of two styles of factory method because there are two completely separate situations where they are appropriate.

    The first type - which seems to coincide with what you are being led to call a simple factory comes about when you have a relatively complicated object that can be difficult to create because of it's complexity.

    The classic example here is the Pizza class which has a PizzaConstructor class (or some similar name) where much of the clevers required to build the Pizza object is encoded into the Constructor.

    There's a nice discussion here but the salient point is that this form puts the clevers of how to construct the Pizza in a Factory rather than bogging down the Pizza class.

    With this technique you can make constructor code that is much clearer than it would normally be.

    Pizza pizza = PizzaFactory.addTopping(Cheese)
        .addTopping(Anchovies)
        .thickCrust()
        .stuffedCrust(Gruyere)
        .stoneBaked()
        .buildPizza();
    

    The second situation for the use of factories is when you need your class to be able to actually make objects of a supplied type. This is difficult without the user supplying a factory mechanism for you to use. The user then supplies a factory mechanism of some sort, perhaps a factory object or maybe they extend your abstract class and provide a concrete constructor method.

提交回复
热议问题