What is the difference between Builder Design patt

2019-01-04 04:17发布

What is the difference between the Builder design pattern and the Factory design pattern?

Which one is more advantageous and why ?

How do I represent my findings as a graph if I want to test and compare/contrast these patterns ?

25条回答
乱世女痞
2楼-- · 2019-01-04 04:56

A factory is simply a wrapper function around a constructor (possibly one in a different class). The key difference is that a factory method pattern requires the entire object to be built in a single method call, with all the parameters pass in on a single line. The final object will be returned.

A builder pattern, on the other hand, is in essence a wrapper object around all the possible parameters you might want to pass into a constructor invocation. This allows you to use setter methods to slowly build up your parameter list. One additional method on a builder class is a build() method, which simply passes the builder object into the desired constructor, and returns the result.

In static languages like Java, this becomes more important when you have more than a handful of (potentially optional) parameters, as it avoids the requirement to have telescopic constructors for all the possible combinations of parameters. Also a builder allows you to use setter methods to define read-only or private fields that cannot be directly modified after the constructor has been called.

Basic Factory Example

// Factory
static class FruitFactory {
    static Fruit create(name, color, firmness) {
        // Additional logic
        return new Fruit(name, color, firmness);
    }
}

// Usage
Fruit fruit = FruitFactory.create("apple", "red", "crunchy");

Basic Builder Example

// Builder
class FruitBuilder {
    String name, color, firmness;
    FruitBuilder setName(name)         { this.name     = name;     return this; }
    FruitBuilder setColor(color)       { this.color    = color;    return this; }
    FruitBuilder setFirmness(firmness) { this.firmness = firmness; return this; }
    Fruit build() {
        return new Fruit(this); // Pass in the builder
    }
}

// Usage
Fruit fruit = new FruitBuilder()
        .setName("apple")
        .setColor("red")
        .setFirmness("crunchy")
        .build();

It may be worth comparing the code samples from these two wikipedia pages:

http://en.wikipedia.org/wiki/Factory_method_pattern
http://en.wikipedia.org/wiki/Builder_pattern

查看更多
Evening l夕情丶
3楼-- · 2019-01-04 04:56

The builder design pattern describes an object that knows how to craft another object of a specific type over several steps. It holds the needed state for the target item at each intermediate step. Think what StringBuilder goes through to produce a final string.

The factory design pattern describes an object that knows how to create several different but related kinds of object in one step, where the specific type is chosen based on given parameters. Think of the serialization system, where you create your serializer and it constructs the desired in object all in one load call.

查看更多
仙女界的扛把子
4楼-- · 2019-01-04 04:56
  • Constructing a complex object step by step : builder pattern

  • A simple object is created by using a single method : factory method pattern

  • Creating Object by using multiple factory method : Abstract factory pattern

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-04 04:56

Builder and Abstract Factory have meant for different purposes. Depending on right use case, you have to select suitable design pattern.

Builder salient features:

  1. Builder pattern builds a complex object using simple objects and using a step by step approach
  2. A Builder class builds the final object step by step. This builder is independent of other objects
  3. Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
  4. Some of the parameters might be optional unlike in Factory which forces to send all parameters

Factory (simple Factory) salient features:

  1. Creational pattern
  2. Based on inheritance
  3. Factory returns a Factory Method (interface) which in turn returns Concrete Object
  4. You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
  5. Client always access interface only and you can hide object creation details in Factory method.

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex)

Have a look at related posts:

Keeping builder in separate class (fluent interface)

Design Patterns: Factory vs Factory method vs Abstract Factory

You can refer to below articles for more details:

sourcemaking

journaldev

查看更多
Animai°情兽
6楼-- · 2019-01-04 04:56

Abstract Factory & Builder pattern are both Creational patterns but with different intent.

Abstract Factory Pattern emphasizes object creation for families of related objects where:

  • Each family is a set of classes derived from a common base class/Interface.
  • Each object is returned immediately as a result of one call.

Builder pattern focuses on constructing a complex object step by step. It decouples the representation from the process of constructing the complex object, so that the same construction process can be used for different representations.

  • Builder object encapsulates configuration of the complex object.
  • Director object knows the protocol of using the Builder, where the protocol defines all logical steps required to build the complex object.
查看更多
不美不萌又怎样
7楼-- · 2019-01-04 04:58

One striking difference between Builder & factory which I could make out was the following

suppose we have a car

class Car
{
  bool HasGPS;
  bool IsCityCar;
  bool IsSportsCar;
  int   Cylenders;
  int Seats;

  public:
     void Car(bool hasGPs=false,bool IsCityCar=false,bool IsSportsCar=false, int Cylender=2, int Seats=4);
 };

In the above interface we can get car by the following way :

 int main()
 {
    BadCar = new Car(false,false,true,4,4);
  }

but what if, some exception happens while creating the Seats ??? YOU WILL NOT GET THE OBJECT AT ALL // BUT

suppose you have implementation like the following

class Car
 {
    bool mHasGPS;
    bool mIsCityCar;
    bool mIsSportsCar;
    int mCylenders;
    int mSeats;

 public:
    void Car() : mHasGPs(false), mIsCityCar(false), mIsSportsCar(false), mCylender(2), mSeats(4) {}
    void SetGPS(bool hasGPs=false)  {mHasGPs = hasGPs;}
    void SetCity(bool CityCar)  {mIsCityCar = CityCar;}
    void SetSports(bool SportsCar)  {mIsSportsCar = SportsCar;}
    void SetCylender(int Cylender)  {mCylenders = Cylender;}    
    void SetSeats(int seat) {mSeats = seat;}    
};

 class CarBuilder 
 {
    Car* mCar;
public:
        CarBuilder():mCar(NULL) {   mCar* = new Car();  }
        ~CarBuilder()   {   if(mCar)    {   delete mCar;    }
        Car* GetCar()   {   return mCar; mCar=new Car();    }
        CarBuilder* SetSeats(int n) {   mCar->SetSeats(n); return this; }
        CarBuilder* SetCylender(int n)  {   mCar->SetCylender(n); return this;  }
        CarBuilder* SetSports(bool val) {   mCar->SetSports(val); return this;  }
        CarBuilder* SetCity(bool val)   {   mCar->SetCity(val); return this;    }
        CarBuilder* SetGPS(bool val)    {   mCar->SetGPS(val); return this; }
}

Now you can create like this

 int main()
 {
   CarBuilder* bp =new CarBuilder;
    Car* NewCar  = bp->SetSeats(4)->SetSports(4)->SetCity(ture)->SetGPS(false)->SetSports(true)->GetCar();

     bp->SetSeats(2);

     bp->SetSports(4);

     bp->SetCity(ture);

     bp->SetSports(true)

     Car* Car_II=  bp->GetCar();

  }

Here in the second case , even if one operation fails you would still get the Car.

May be that car does not works perfectly later but , you would have the object.

Because Factory Method gives you the Car in single call , whereas the Builder builds one by one.

Although, It depends on the needs of the deign which one to go for.

查看更多
登录 后发表回答