javascript设计模式 – 模板方法模式原理与用法实例分析
作者:李小强 时间:2024-11-02 16:31:52
本文实例讲述了javascript设计模式 – 模板方法模式原理与用法。分享给大家供大家参考,具体如下:
介绍:模板方法模式是结构最简单的行为型设计模式,在其结构中只存在父类与子类之间的继承关系。使用模板方法模式,可以将一些复杂流程的实现步骤封装在一系列基本方法中。
定义:定义一个操作中算法的框架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。模板方法是一种类行为型模式。
场景:我们设计一个游戏机,用来运行不同的游戏,
示例:
var Game = function(){
this.play = function(){
this.initialize();
this.startPlay();
this.endPlay();
this.uninstall();
}
this.uninstall = function(){
console.log('uninstall Game')
}
}
var CrossFire = function(){
this.initialize = function(){
console.log('CrossFire initialize')
}
this.startPlay = function(){
console.log('CrossFire startPlay')
}
this.endPlay = function(){
console.log('CrossFire endPlay')
}
}
CrossFire.prototype = new Game();
var LeagueofLegends = function(){
this.initialize = function(){
console.log('LeagueofLegends initialize')
}
this.startPlay = function(){
console.log('LeagueofLegends startPlay')
}
this.endPlay = function(){
console.log('LeagueofLegends endPlay')
}
}
LeagueofLegends.prototype = new Game();
var cf = new CrossFire();
cf.play();
// CrossFire initialize
// CrossFire startPlay
// CrossFire endPlay
// uninstall Game
var lol = new LeagueofLegends();
lol.play();
// LeagueofLegends initialize
// LeagueofLegends startPlay
// LeagueofLegends endPlay
// uninstall Game
在这个例子里,Game称为抽象类,抽象类内部定义了一个模板方法play,play的内部定义了算法的架构,算法的执行顺序,只有子类将步骤补齐后才能执行模板方法。
LeagueofLegends,CrossFire这两个类称为子类,继承自Game,他们的任务是实现模板方法中的步骤。
initialize,startPlay,endPlay,uninstall称为基本方法,用来具体实现每个步骤
模板方法模式总结:
优点:
* 模板方法模式是一种代码复用技术,将公共行为放在父类中,而通过其子类来实现不同的行为,他鼓励恰当使用继承来实现代码复用。
* 模板方法可以实现一种反向控制结构,通过子类覆盖父类的方法来决定某一步骤是否执行。
缺点:
* 需要为每一个基本方法的不同实现提供一个子类,如果父类中可变的基本方法太多,将会导致类的个数增加,系统更加庞大。
适用场景:
* 对一些复杂的算法进行分割,将其中固定不变的布冯设计为模板方法和父类基本方法,改变的细节由子类实现。
* 各子类的公共行为应当被提取出来并集中带一个父类中,利于代码复用。
* 需要子类决定父类的某个步骤是否执行,实现子类对父类的反向控制。
希望本文所述对大家JavaScript程序设计有所帮助。
来源:http://www.isjs.cn/?p=1007