模板方法模式

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

定义一个算法操作的骨架(模板方法),延迟某些步骤由具体子类来实现,而不改变整个操作的算法结构。

模板类

/**
 * 模板类
 */
public abstract class AbstractEngineering {
    /**
     * 模板方法
     */
    public void papers() {
        // Common papers:
        math();
        softSkills();
        // Specialized Paper:
        specialPaper();
    }

    private void math() {
        System.out.println("Mathematics");
    }

    private void softSkills() {
        System.out.println("SoftSkills");
    }

    // 抽象方法由实现类提供
    public abstract void specialPaper();
}

定义模板方法,模板方法定义整个算法结构

实现类

public class ComputerScience extends AbstractEngineering {
    @Override
    public void specialPaper() {
        System.out.println("Object Oriented Programming");
    }
}

public class Electronics extends AbstractEngineering {
    @Override
    public void specialPaper() {
        System.out.println("Digital Logic and Circuit Theory");
    }
}

执行

public class Test {
    public static void main(String[] args) {
        AbstractEngineering cs = new ComputerScience();
        cs.papers();

        AbstractEngineering es = new Electronics();
        es.papers();
    }
}

类图

template-method.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容