了解工厂方法设计模式

Building things can be tough when you can’t anticipate what type of objects you’ll need to create or how to create them. Take for example a factory which manufactures a large number of products. Each product can be made up of any number of components in their inventory. The workers know what’s in the inventory but don’t necessarily know beforehand what kind of products they will be making. The Factory Method design pattern can be applied to similar situations in programming where you have a set of component classes but won’t know exactly which one you’ll need to instantiate until runtime. In this article I’ll show you how the Factory Method pattern can be used to create different objects, without knowing beforehand what sort of objects it needs to create or how the object is created.

当您无法预料需要创建哪种类型的对象或如何创建对象时,进行构建可能会很困难。 以一家生产大量产品的工厂为例。 每个产品都可以由其库存中的任何数量的组件组成。 工人知道库存中有什么,但不一定事先知道他们将要生产哪种产品。 工厂方法设计模式可以应用于类似的情况,在编程中您具有一组组件类,但是直到运行时才确切知道需要实例化哪个组件类。 在本文中,我将向您展示如何使用Factory Method模式创建不同的对象,而无需事先知道需要创建什么样的对象或如何创建对象。

工厂方法 (The Factory Method)

The Factory Method pattern is a design pattern used to define a runtime interface for creating an object. It’s called a factory because it creates various types of objects without necessarily knowing what kind of object it creates or how to create it.

Factory Method模式是一种设计模式,用于定义用于创建对象的运行时接口。 之所以称为工厂,是因为它创建各种类型的对象,而不必知道它创建的是哪种对象或如何创建。

Here’s an example of how the Factory Pattern works. Assume you have a ProductFactory class which creates a new type of product:

这是工厂模式如何工作的示例。 假设您有一个ProductFactory类,它创建一种新的产品类型:

<?php
class ProductFactory
{
    public static function build($type) {
        // assumes the use of an autoloader
        $product = "Product_" . $type;
        if (class_exists($product)) {
            return new $product();
        }
        else {
            throw new Exception("Invalid product type given.");
        }
    } 
}

By defining build() as a factory method, you now have an interface through which you can create different products on the fly.

通过将build()定义为工厂方法,您现在有了一个接口,可以通过该接口动态创建不同的产品。

<?php
// build a new Product_Computer type
$myComputer = ProductFactory::build("Computer");
// build a new Product_Tablet type
$myTablet = ProductFactory::build("Tablet");

The Factory Method pattern is generally used in the following situations:

工厂方法模式通常用于以下情况:

  • A class cannot anticipate the type of objects it needs to create beforehand.

    类无法预期需要预先创建的对象的类型。
  • A class requires its subclasses to specify the objects it creates.

    一个类需要其子类来指定其创建的对象。
  • You want to localize the logic to instantiate a complex object.

    您想本地化逻辑以实例化一个复杂的对象。

The Factory Method pattern is useful when you need to abstract the creation of an object away from its actual implementation. Let’s say the factory will be building a “MobileDevice” product type. A mobile device could be made up of any number of components, some of which can and will change later, depending on advances in technology.

当您需要从对象的实际实现中抽象出对象的创建时,Factory Method模式非常有用。 假设工厂将构建“ MobileDevice”产品类型。 移动设备可以由任意数量的组件组成,其中某些组件可以并且将来会更改,这取决于技术的进步。

<?php
class Product_MobileDevice
{
    private $components;

    public function __construct() {
        // this device uses a 7" LCD
        $this->addComponent(ProductFactory::build("LCD", 7));
        // and features an 1GHz ARM processor  
        $this->addComponent(ProductFactory::build("CPU_ARM", 1));
    }
...
}

// build a new Product_MobileDevice type
$myDevice = ProductFactory::build("MobileDevice");
$myDevice->use();

The logic to create a Product_MobileDevice object has been encapsulated into the class itself. If you want to exchange the 7″ LCD screen with a 10″ Touch_Screen later, you can make the isolated change in the MobileDevice class without affecting the rest of your application.

创建Product_MobileDevice对象的逻辑已封装到类本身中。 如果以后要用10英寸的Touch_Screen交换7英寸的LCD屏幕,则可以在MobileDevice类中进行单独的更改,而不会影响应用程序的其余部分。

使用其他工厂的工厂 (Factories Using Other Factories)

Because the instantiation of an object is encapsulated, it could also use factories itself. To further expand on the idea of abstract object creation, let’s use a non-software engineering analogy. An automotive factory manufactures vehicles of a specific make, model, and color, but it may not produce all the necessary parts itself that are required to build the vehicle. In other words, it delegates the production of these parts out to other factories which it then uses to build new vehicles.

因为对象的实例化是封装的,所以它也可以使用工厂本身。 为了进一步扩展抽象对象创建的思想,让我们使用非软件工程类比。 汽车制造厂生产特定品牌,型号和颜色的汽车,但它本身可能无法生产制造该汽车所需的所有必要零件。 换句话说,它将这些零件的生产委托给其他工厂,然后用于制造新车辆。

Under this scenario, a vehicle factory might look like this:

在这种情况下,车辆工厂可能如下所示:

<?php
class VehicleFactory
{
    public static function build($make, $model, $color) {
        $vehicle = new Vehicle;

        // vehicle needs a chassis which is produced by another factory
        $vehicle->addPart(VehicleChassisFactory::build($make, $model));
        // needs an engine built by someone else
        $vehicle->addPart(VehicleEngineFactory::build($make, $model));
        // it needs a bodykit made by another factory
        $vehicle->addPart(VehicleBodyFactory::build($make, $model, $color));
        // and interiors are made by... you guessed it, someone else 
        $vehicle->addPart(VehicleInteriorFactory::build($make, $model, $color));

        // ...add more parts

        return $vehicle;
    }
}

// build a new white VW Amarok
$myCar = VehicleFactory::build("Volkswagon", "Amarok", "white");
$myCar->drive();

Voilà! A shiny new car. The VehicleFactory class produces a vehicle of a specified make, model and color, but acquired the various parts produced by other factory methods.

瞧! 一辆闪亮的新车。 VehicleFactory类生产具有指定制造商,型号和颜色的车辆,但是获得了通过其他工厂方法生产的各种零件。

摘要 (Summary)

In this article you’ve learned how the Factory Method pattern can be used to localize the construction of different objects and to allow you to create objects without knowing specifically what type you’ll need beforehand. You also saw also factory methods can use other factory methods to create objects objects and define what objects they produce.

在本文中,您学习了如何使用Factory Method模式来本地化不同对象的构造,并允许您在不事先知道具体需要哪种类型的情况下创建对象。 您还看到工厂方法也可以使用其他工厂方法来创建对象对象并定义它们产生的对象。

Image via yuminglin / Shutterstock

图片来自yuminglin / Shutterstock

翻译自: https://www.sitepoint.com/understanding-the-factory-method-design-pattern/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值