简体   繁体   中英

Builder Pattern more than one director

I want to know if a Builder Pattern can have more than one Director? Because I have to build a object that have different implementations.

For example,

Sometime the object is constructed from slugs so I have to use a foreach to add different slugs to object.

//Director 1

function build ($obj) {
    foreach($slugs as $slug) {
        $object = $obj->createObject($slug);
        $object->buildItem1();
        $object->buildItem2();
    }
}

But, other times the object is built out every lines.

//Director 2

function build ($obj) {
    $object = $obj->createObject();
    $object->buildItem1();
    $object->buildItem2();
}

You wrote:

I have to build a object that have different implementations.

Aren't objects that have different implementations objects from different classes?

According to several sources the builder pattern has a Director object who does the actual building. You instantiate an concrete-builder object, which can build the product you want, and ask the director to use the concree-builder to build the object.

The concrete-builder is derived from class builder or imlements an IBuild interface. The director knows how to build builders, and will call the appropriate functions to build the product.

A typical example is if you want to be able to build motorcycles and cars. You have a class or interface VehicleBuilder with two derived classes MotorCycleBuilder and CarBuilder. Depending on what you want as a product you construct a MotorCycleBuilder or a CarBuilder and order the directory to build the product.

Back to your question. You want to be able to build two kinds of products: product A and product B. The products might be of the same class, or of a different class.

If you want to use the builder pattern for this, you'll have to design an ABuilder and a BBuilder. ABuilders will deliver product A and BBuilders will deliver product B. Both ABuilder and BBuilder are derived from Builder, or have at least a common interface like IBuild

Now once you've decided whether you want to build a product A or a product B you do the following:

Builder myBuilder = isProductARequested ? new ABuilder() : new BBuilder();
Director myDirector = new Director();
Product myProduct = myDirector.Build(myBuilder);

Now suppose to build your product you need to do BuildStep1() and BuildStep2(), then both ABuilder and BBuilder should implement these functions and an IBuild interface with these functions, or derive from an abstract class with function BuildStep1() and BuildStep2().

The actual implementations of BuildStep1 and BuildStep2 will make sure a different product is build. These products might be of the same type, or of a different type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM