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

【JavaScript设计模式与开发实践】第十一章 - 模板方法模式 #56

Open
Kelichao opened this issue Jul 13, 2017 · 0 comments

Comments

@Kelichao
Copy link
Owner

Kelichao commented Jul 13, 2017

模板方法模式使用

模板方法模式是将一套逻辑的各个步骤都规定好,你只需要填写不同参数与回调函数体即可。

// 建立一个请求ajax并渲染数据的一个模板
var RenderDom = function (obj) { 

    // 安全构造函数
    if(!(this instanceof RenderDom)) {
        return new RenderDom(obj);
    }
};

RenderDom.prototype.getData = function () {
    console.log('请求异步数据');
};

// 渲染模板生成html字符串
RenderDom.prototype.renderTemp = function () { 
    console.error("还未确定渲染模板");
};

// 渲染模板
RenderDom.prototype.input = function () { 
    console.error("还未确定填充对象");
};

RenderDom.prototype.init = function () {
    this.getData();
    this.renderTemp();
    this.input();
};

// 开始继承,这边就不再需要罗列初始化步骤
var F7Render = function (obj) {};
F7Render.prototype = new RenderDom();
F7Render.prototype.renderTemp = function() {
    console.log("div1")
};
F7Render.prototype.input = function () {
    console.log("input2")
};

var f7 = new F7Render();
f7.init();

钩子方法的使用

  • 钩子方法(hook)可以用来解决这个问题,放置钩子是隔离变化的一种常见手段
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