Last active
March 22, 2016 11:33
-
-
Save fwon/36d6d81ad5a3d9955487 to your computer and use it in GitHub Desktop.
设计模式代码示例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*代理模式*/ | |
var mult = function(){ | |
var a = 1; | |
for(var i = 0, l = arguments.length; i < l; i++) { | |
a = a * arguments[i]; | |
} | |
return a; | |
} | |
var proxyMulti = (function(){ | |
var cache = {}; | |
return function(){ | |
var args = Array.prototype.join.call(arguments, ','); | |
if (args in cache) { | |
return cache[args]; | |
} | |
return cache[args] = mult.apply(this, arguments); | |
} | |
})(); | |
//代理模式工厂 | |
var mult = function(){ | |
var a = 1; | |
for(var i = 0, l = arguments.length; i < l; i++) { | |
a = a * arguments[i]; | |
} | |
return a; | |
} | |
var plus = function(){ | |
var a = 1; | |
for(var i = 0, l = arguments.length; i < l; i++) { | |
a = a + arguments[i]; | |
} | |
return a; | |
} | |
var createProxyFactory = function(fn) { | |
var cache = {}; | |
return function(){ | |
var args = Array.prototype.join.call(arguments, ','); | |
if (args in cache) { | |
return cache[args]; | |
} | |
return cache[args] = fn.apply(this, arguments); | |
} | |
} | |
var proxyMulti = createProxyFactory(multi); | |
var proxyPlus = createProxyFactory(plus); | |
proxyMulti(1,2,3); | |
proxyPlus(1,2,3); | |
/*命令模式*/ | |
var MoveCommand = function(receive, pos) { | |
this.receive = receive; | |
this.pos = pos; | |
} | |
//通常会封装一个execute方法 | |
MoveCommand.prototype.execute = function() { | |
this.receive.start('left', this.pos, 1000, 'strongEaseOut'); | |
} | |
var moveCommand; | |
moveBtn.onclick = function() { | |
var animate = new Animate(ball); | |
moveCommand = new MoveCommand(animate, pos.value); | |
moveCommand.execute(); | |
} | |
/*模板方法模式*/ | |
//用在类的继承中,父类封装好一个方法,由子类直接调用,不必重写。 | |
//必要时可以在父类中加加钩子方法,满足子类特殊性 | |
/*开放-封闭原则*/ | |
//重写window.onload方法 | |
Function.prototype.after = function(fn){ | |
var _self = this; | |
return function() { | |
var ret = _self.apply(this, arguments); | |
fn.apply(this, arguments); | |
return ret; | |
} | |
} | |
window.onload = (window.onload || function(){}).after(function(){ | |
//do something | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment