Template method mode vs Builder Mode

Source: Internet
Author: User
Tags abstract inheritance


Come today with two design mode Showdown, template method vs Builder mode.
First, look at the definition of the template method pattern: Define the skeleton of an algorithm in an operation, and defer some steps into the subclass. The template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm. Its UML diagram is as follows:


AbstractClass is an abstract class, in fact, it is an abstract template, it gives a top-level logical skeleton, and the logical composition of the steps in the corresponding abstract operation, deferred to sub-class Concreteclass implementation.
What is the main feature of the template method pattern?
The template method pattern is the advantage of removing duplicate code from the class by moving the invariant behavior to the parent class (Super Class). The template method pattern is a platform that provides a code reuse. When a sequence of steps is encountered that requires execution, the process is the same at a high level, but the implementation of some steps may not at the same time consider using the template method pattern. That is, when immutable and mutable behavior is mixed together in the implementation of a subclass of a method, the invariant behavior repeats itself in the subclass. The ability to move these behaviors to a single place through a template-mode approach helps the subclass to get rid of the repetitive, unchanging behavior of entanglement.
Here is a small example of my code: #include <iostream>
using namespace Std;
Class Abstract2 {public:virtual ~abstract2 () {} void Templatemethod () {__methoda (); __methodb (); __methodc ();} private: void __methoda () {cout<< "1, select '" <<_answera () << "'" &LT;&LT;ENDL;} void __methodb () {cout<< "2, select" "<<_answerb () <<" ' "&LT;&LT;ENDL;} void __methodc () {cout<< "3, select '" <<_answerc () << "'" <<endl;} protected:abstract2 () {} virtual String _answera () = 0;    Virtual String _answerb () = 0; Virtual String _answerc () = 0; };
Class Concretea2:public Abstract2 {protected:virtual string _answera () {return "A";} virtual string _answerb () {retur n "B";  } virtual String _answerc () {return ' C '; } };
Class Concreteb2:public Abstract2 {protected:virtual string _answera () {return "B";} virtual string _answerb () {retur n "B";  } virtual String _answerc () {return "A"; } }; int main () {Abstract2 *pa (new ConcreteA2); Pa->templatemethod (); Delete pa; pa = new ConcreteB2; pa->templatemethod (); System ("pause"); return 0; }
Take a look at the builder pattern, which is defined as separating the construction of a complex object from its representation so that the same build process can create different representations. Its UML diagram is as follows:


Builder is the abstract interface that is specified for each part of the product object, ConcreteBuilder is the concrete builder, implements the builders interface, constructs and assembles the individual parts. Director is the conductor, it is to build a control construction process, but also use it to isolate the user and the construction process of the association.
So what are the characteristics of it? The builder pattern separates the construction of a complex object from its representation, allowing the same build process to create different representations. It allows the user to specify only the types that need to be constructed to get them, and the process and details of the concrete construction do not need to be known. The benefit of the builder model is that the construction code is separated from the presentation code, and because the builder hides how the product is assembled, the base needs to change the internal representation of a product, only to define a specific command. It is primarily used to create complex objects in which the order in which they are built is usually stable, but the construction of objects within them often faces complex changes.
Here is a small example of what I have written:
#include <iostream>
using namespace Std;
Class automobile//abstract Car class {public:virtual ~automobile () {cout<< "Destruction Automobile" &LT;&LT;ENDL;} virtual        void Buildwheel () = 0;        Build wheel virtual void buildbody () = 0;    Build body virtual void buildvehicle () = 0; Build the car shell protected:automobile () {}};
Class Car:public Automobile {public:virtual void Buildwheel () {cout<< "build the Wheel of Car" <<endl;} virt UAL void Buildbody () {cout<< "build the body of car" <<endl;} virtual void Buildvehicle () {cout<< "build The vechicle of car <<endl; } ~car () {cout<< "Destruction Car" &LT;&LT;ENDL;};
Class Truck:public Automobile {public:virtual void Buildwheel () {cout<< "build the Wheel of Truck" <<endl;} virtual void Buildbody () {cout<< "build the body of Truck" <<endl;} virtual void Buildvehicle () {cout<&lt ;" Build the vechicle of Truck "<<endl; } ~truck () {cout<< "Destruction Truck" &LT;&LT;ENDL;};
Class Director//conductor category, command vehicle production process {Public:director (Automobile *p):p am (p) {} void Build () {pam->buildbody (); pam->b Uildwheel ();  Pam->buildvehicle (); } private:automobile *pam; };
int main () {Truck *ptk (new Truck); Director D (pTk); D.build (); Delete pTk; System ("pause"); return 0; }
I may think that there is nothing in the same way between the two patterns, so what are the differences and similarities?
Here are some of my views, the beginner design mode, if there is not correct, also hope to point out.
First, the template method pattern is the behavioral pattern, and the builder pattern is the creation pattern.
Behavioral patterns are designed to assign responsibilities between algorithms and objects, not only to describe the patterns of objects or classes, but also to describe how they communicate, and to carve out complex control flows that are difficult to track at run time, and they divert your attention from the control flow to the relationship between objects. The Behavioral class pattern uses the inheritance mechanism to assign behaviors between classes, such as template Method and interpreter; The behavior object pattern uses object compositing instead of inheritance. Some behavioral object patterns describe how a set of mutually-equivalent objects work together to accomplish tasks that any one of these objects cannot accomplish alone, such as mediator, Chain of Responsibility, strategy Other behavioral object patterns often encapsulate behavior encapsulation in an object and assign the request to it.
The Create pattern abstracts the instantiation process. They help a system independent of how to create, assemble, and represent those objects. A class-creation pattern uses inheritance to change the class that is instantiated. An object-creation pattern instantiates the delegate to another object.
In other words, the template method pattern is used to control the communication of objects and classes, and the builder pattern is used to create objects.
So they really don't have a connection. Personally think not.
In my opinion, the builder pattern also embodies the template approach, because the builder class defines the methods that ConcreteBuilder must override or need to have, which means that there are methods that are defined in builder that can be implemented in the builder class, It can also be deferred to subclasses. Using the two examples above, the important function of the Abstract2 class in the template method Templatemethod is similar to the function build in the Director class in the builder pattern, which defines the skeleton of the execution of the method. So the template-based approach pattern is a behavioral pattern, and the builder pattern is the creation model to talk about, what is the difference between them? I think that in the framework of the implementation method, the builder pattern is used in the combination of methods, and the template method pattern is inherited, we all know that the combination is better than inheritance, so I think the builders are more flexible, but also can avoid the inheritance caused by various problems, such as code inflation, too much responsibility, difficult to maintain and so on.
PS: Personally, the conductor class is the core of the construction mode and the soul, if there is no command class, then the builder mode can be retired into a pattern method mode, details of my other blog: the builder model of the role of the conductor class, http://blog.csdn.net/ljianhui/ article/details/8280594;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.