why factory pattern and when to use factory pattern

1 factory pattern本质上就是对对象创建进行抽象

抽象的好处是显然的,可以方便用户去获取对象。

2 使用factory pattern的时机

第一,当一个对象的创建依赖于其它很多对象的时候,即一个对象的创建背后存在很多的依赖关系,如果用户要自己去创建这个对象的话,需要首先花很多时间去理清楚这个依赖关系,很是麻烦。如果用factory pattern的话,那么用户在创建这个对象的时候,就可以不用理会这些复杂的依赖关系了。直接让factory代劳就可以了。

例子:很多情况下依赖关系比下面的例子要复杂很多。

in PHP: Suppose you have a House object, which in turn has a Kitchen and a LivingRoom object, and the LivingRoom object has a TV object inside as well.

The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your House fails creating you will probably spend some time trying to isolate exactly what is failing.

The alternative is to do the following (dependency injection, if you like the fancy term):

$TVObj = new TV($param1, $param2, $param3);
$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
$KitchenroomObj = new Kitchen($param1, $param2);
$HouseObj = new House($LivingroomObj, $KitchenroomObj);

Here if the process of creating a House fails there is only one place to look, but having to use this chunk every time one wants a new House is far from convenient. Enter the Factories:

class HouseFactory {
    public function create() {
        $TVObj = new TV($param1, $param2, $param3);
        $LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
        $KitchenroomObj = new Kitchen($param1, $param2);
        $HouseObj = new House($LivingroomObj, $KitchenroomObj);

        return $HouseObj;
    }
}

$houseFactory = new HouseFactory();
$HouseObj = $houseFactory->create();

第二,factory mode可以带来很好的测试性

???

原文地址:https://www.cnblogs.com/hustdc/p/6435371.html