Have you ever buy a computer online, maybe from dell? In dell’s website, we just need to follow its process to order the accessories you need, then you can get your own computer configuration. Of course, you can’t get the real computer until you pay it
Here, you direct the producer to produce your own computer through the dell website. Ok, three roles here, you, dell website and the real producer.
If we change the You to Director, DellWebsite to Builder and RealProducer to ConcreteBuilder, then this class diagram will be totally like that in a pattern called builder, and this is the topic today.
The intent of this pattern is as follows.
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
–By GOF BOOK
In our example, the computer is a complex object, and we use the accessories’ description for its representation, and the construction process is the same.
So, our class diagram will be as follows.
Here, we use the description for the return value of getProduct() method in ComputerBuilder.
Now, the Director controls how to produce the computer in orderComputer() method, and the ComputerBuilder is the real action taker, it produces the real computer you want. If you want to get another kind of computer, you need to add another concrete builder class to build your dream computer
In our code, we can call produce the computer in this way.
- var builder:Builder = new ComputerBuilder();
- var director:Director = new Director(builder);
Further more, you can compare this pattern with the template method. When you join the Director and the Builder interface together, it looks like the template method, isn’t it?
Download Full Project