Design pattern seven, template method pattern

The template method pattern defines the skeleton of an algorithm in operation, and delays some steps to subclasses. The template method allows subclasses to redefine certain specific steps of an algorithm without changing the structure of the algorithm.

The template method provides a good code reuse platform by moving the invariant behavior to the super class and removing the repeated code of the subclass.

public abstract class TestPaper {
    
    
    public abstract void Answer1(); //抽象行为,放到子类去实现
    public abstract void Answer2();

    public void Test1() {
    
                       //模板方法,重复的部分都放在父类,而逻辑的组成都是抽象行为,推迟到子类实现
        System.out.print("Test1 ");
        Answer1();
    }

    public void Test2(){
    
    
        System.out.print("Test2 ");
        Answer2();
    }
}

public class TestPaperA extends TestPaper{
    
    
    @Override
    public void Answer1() {
    
    
        System.out.println("studentA   Test1选a");     //子类各自的抽象行为的不同实现
    }

    @Override
    public void Answer2() {
    
    
        System.out.println("studentA   Test2选b");
    }
}

public class TestPaperB extends TestPaper{
    
    
    @Override
    public void Answer1() {
    
    
        System.out.println("studentB   Test1选c");
    }

    @Override
    public void Answer2() {
    
    
        System.out.println("studentB   Test2选d");
    }

    public static void main(String[] args) {
    
    
        TestPaper studentA = new TestPaperA();  //声明为父类,利用多态进行复用
        studentA.Test1();
        studentA.Test2();

        TestPaper studentB = new TestPaperB();
        studentB.Test1();
        studentB.Test2();
    }
}

Output:

Test1 studentA   Test1选a
Test2 studentA   Test2选b
Test1 studentB   Test1选c
Test2 studentB   Test2选d

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629288