Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

模板方法模式 #214

Open
louzhedong opened this issue Jun 2, 2020 · 0 comments
Open

模板方法模式 #214

louzhedong opened this issue Jun 2, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

模板方法模式

定义:

定义一个操作中的算法的框架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

优点:

封装不变部分,扩展可变部分

提取公共部分代码,便于维护

行为由父类控制,子类实现

缺点:

按照我们的设计习惯,抽象类负责声明最抽象、最一般的事物属性和方法,实现类完成具体的事物属性和方法。但是模板方法模式却颠倒了,抽象类定义了部分抽象方法,由子类实现,子类执行的结果影响了父类的结果,也就是子类对父类产生了影响,这在复杂的项目中,会带来代码阅读的难度,而且也会让新手产生不适感。

实现
JavaScript
var AbstractClass = function() {}

AbstractClass.prototype.method1 = function() {};
AbstractClass.prototype.method2 = function() {};
AbstractClass.prototype.method3 = function() {};

AbstractClass.prototype.init = function() {
  this.method1();
  this.method2();
  this.method3();
};


var ConcreteClass = function() {}
ConcreteClass.prototype = new AbstractClass();

ConcreteClass.prototype.method1 = function() {};
ConcreteClass.prototype.method2 = function() {};
ConcreteClass.prototype.method3 = function() {};

var concrete = new ConcreteClass();
concrete.init();
Java
/**
 * 抽象模板类
 **/
public abstract class AbstractClass {
    protected abstract void doSomething();

    protected abstract void doAnything();

    // 模板方法
    public void templateMethod() {
        this.doSomething();
        this.doAnything();
    }
}

/**
 * 具体模板类
 **/
public class ConcreteClass extends AbstractClass{
    @Override
    protected void doAnything() {
    }
    @Override
    protected void doSomething() {
    }
}

/**
 * 场景类
 **/
public class Client {
    public static void main(String[] args) {
        AbstractClass concreteClass = new ConcreteClass();
        concreteClass.templateMethod();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant