Study Notes on design patterns (14)------ Template Method(Template Method) Mode
Gof:Defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
Inheritance is one of the three major features (encapsulation, inheritance, and polymorphism) of OO ideas. Inheritance is for better code reuse, but today, more and more OO methodology masters come to the conclusion that combination rather than inheritance is preferred. The template method mode is one of the simplest modes currently learned. This is also a common mode. Inheritance is fully applied in the template method mode. In my opinion, the template method mode is inheritance. In a drawing program, I wrote a method called Drow, which will draw the image I need. The template method mode can help me do this, because a reference is used to call a method, and the object pointed to by this reference belongs to a derived class.
Below is the Template MethodMode UMLFigure:
The following is the JavaCode:
Define an abstract class to define the skeleton of an algorithm. Here it is abstract Drow.
Package templatemethod;
Public abstract class shapetemplate
{
Public abstract void Drow (); // Template Method
} // End abctract class shape
Package templatemethod;
A specific class is derived, and the method Drow is implemented in a specific class.
Public class square extends shapetemplate
{
@ Override
Public void Drow ()
{
System. Out. println ("draw a square ");
} // End Drow ()
} // End class Square
Package templatemethod;
Test code:
Public class templatemethodpattern
{
Private shapetemplate square;
Public templatemethodpattern ()
{
Square = New Square ();
} // End templatemethodpattern ()
Public void showtemplatemethodpattern ()
{
Square. Drow ();
} // End showtemplatemethodpattern ()
Public static void main (string [] ARGs)
{
System. Out. println ("the template method pattern! ");
Templatemethodpattern TMP = new templatemethodpattern ();
TMP. showtemplatemethodpattern ();
} // End main (...)
} // End class templatemethodpattern
Running result:
The template method pattern!
Draw a square
The template method mode allows us to define the sequence of these steps first, and then reload the steps that need to be changed.
Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 954056