definition : A template method defines an algorithm with some abstract operations, and subclasses redefine these operations to provide specific behavior;
Intent : Defines an algorithmic framework in action that defers some steps to a subclass. The template method pattern allows subclasses to redefine specific algorithm steps without altering the algorithm structure;
Like what
Work () {
① Preparation
② implementation
③ End
}
You can declare the second step implementation as an abstract method, because each person implements a different process
1 Public classtemplatedemo{2 Public Static voidMain (String []atgs) {3Teacher t1=NewDbteacher ();4 t1.work ();5 System.out.println ();6Teacher t2=NewCteacher ();7 t2.work ();8 }9 }Ten One Abstract classteacher{ A //the way the teacher works (it's a process) - Public voidprepared () { -System.out.println ("Ready Whiteboard Pen"); theSystem.out.println ("Turn on the projector"); - } - - Public voidEnd () { +System.out.println ("Turn off the projector"); -SYSTEM.OUT.PRINTLN ("Lock the Door"); + } A //the abstract method is implemented by its subclasses. at Public Abstract voidteaching (); - //Template Method - Public voidWork () { - //1. Preparation before the lecture - prepared (); - //2. Conduct Lectures in teaching (); - //3. End of lecture to end (); + } - } the * classDbteacherextendsteacher{ $ //The implementation of abstract methods for the abstract parent classPanax Notoginseng Public voidTeaching () { -SYSTEM.OUT.PRINTLN ("Open Oracle"); theSystem.out.println ("Writing pl-sql Instructions"); +System.out.println ("Optimize QL instructions"); A } the } + - classCteacherextendsteacher{ $ //The implementation of abstract methods for the abstract parent class $ Public voidTeaching () { -System.out.println ("Open VM"); -System.out.println ("Write C instruction"); theSystem.out.println ("Debug C Program"); - }Wuyi}
Template method Mode