I. Problems
In the analysis and design process of the object-oriented system, we often encounter the following situation: for a business logic (Algorithm Implementation), different details are implemented in different objects, however, the logic (algorithm) Framework (or general application algorithm) is the same. Template provides an implementation framework for this situation.
Ii. Mode
The Template mode implements this by means of inheritance:Place the logic (algorithm) framework in the abstract base class, define the detailed interface, and implement the details in the subclass..
Iii. Code
[Cpp]View plaincopy
- // Abstract the base class to implement a template method
- Class AbstractClass
- {
- Public:
- Virtual ~ AbstractClass ()
- {
- }
-
- // Template method, which is only implemented in the abstract base class
- Void TemplateMethod ()
- {
- This-> PrimitiveOperation1 ();
- This-> PrimitiveOperation2 ();
- }
-
- Protected:
- Virtual void PrimitiveOperation1 () = 0;
-
- Virtual void PrimitiveOperation2 () = 0;
-
- AbstractClass ()
- {
- }
- };
-
- // Specific subclass to implement specific operation details
- Class ConcreteClass1: public AbstractClass
- {
- Public:
- ConcreteClass1 ()
- {
- }
-
- ~ ConcreteClass1 ()
- {
- }
-
- Protected:
- Void PrimitiveOperation1 ()
- {
- Cout <"concreteclass1... PrimitiveOperation1" < }
-
- Void PrimitiveOperation2 ()
- {
- Cout <"concreteclass1... PrimitiveOperation2" < }
- };
-
- // Specific subclass to implement specific operation details
- Class ConcreteClass2: public AbstractClass
- {
- Public:
- ConcreteClass2 ()
- {
- }
-
- ~ ConcreteClass2 ()
- {
- }
-
- Protected:
- Void PrimitiveOperation1 ()
- {
- Cout <"ConcreteClass2. .. PrimitiveOperation1" < }
-
- Void PrimitiveOperation2 ()
- {
- Cout <"ConcreteClass2. .. PrimitiveOperation2" < }
- };
-
-
- Int main ()
- {
- AbstractClass * p1 = new ConcreteClass1 ();
- AbstractClass * p2 = new ConcreteClass2 ();
-
- P1-> TemplateMethod ();
- P2-> TemplateMethod ();
-
- Return 0;
- } The key point is to encapsulate general algorithms in abstract base classes and put different algorithm details into sub-classes for implementation.