The schema definition

Define the algorithm skeleton of an operation, but defer steps to subclasses so that subclasses can redefine specific steps of an algorithm without changing its structure

The class diagram

The point to summarize

  • Template Method pattern is a very basic design pattern, which has a lot of applications in object-oriented systems (such as polymorphism of virtual functions in C++).
  • In addition to the flexibility to respond to changes in substeps, the “don’t call me, let me call you” reverse control structure is a typical use of Template Method

Go language code implementation

Project directory

template.go

Package Template // Workflow interface type Workinterface interface {getUp () Work() Sleep()} // Workflow interface type Worker struct { WorkInterface} // Factory mode, Produces a concrete Worker object (variable) Func newWorker (w WorkInterface) *Worker {return &Worker{w}} // The main process is set (template method), Func (w *Worker) Daily(){w.getup () w.ork () w.leep ()}

coder.go

Package Template import "FMT" // Programmer class defines type Coder struct {} // Programmer method implementation interface func (c *Coder) getUp (){fmt.println (" Coder ") GetUp.") } func (c *Coder) Work(){ fmt.Println("coder is Coding.") } func (c *Coder) Sleep(){ fmt.Println("coder Sleep.") }

teacher.go

package Template import "fmt" type Teacher struct { } func (t *Teacher) GetUp(){ fmt.Println("teacher GetUp.") } func (t  *Teacher) Work(){ fmt.Println("teacher is speaking.") } func (t *Teacher) Sleep(){ fmt.Println("teacher Sleep.") }

template_test.go

 package Template
 ​
 import "testing"
 ​
 func TestWorker_Daily(t *testing.T) {
    worker := NewWorker(&Coder{})
    worker.Daily()
 ​
    worker = NewWorker(&Teacher{})
    worker.Daily()
 }