var type1 = {
switch1Handler: function () {
console.log('handler1 in type1');
},
switch2Handler: function () {
console.log('handler2 in type1');
}
};
var type2 = {
switch1Handler: function () {
console.log('handler1 in type2');
},
switch2Handler: function () {
console.log('handler2 in type2');
}
};
var switch1 = function (type) {
if (type.hasOwnProperty('switch1Handler'))
type.switch1Handler();
else
return false;
};
var switch2 = function (type) {
if (type.hasOwnProperty('switch2Handler'))
type.switch2Handler();
else
return false;
};
switch1(type1);//handler1 in type1
switch1(type2);//handler1 in type2
switch2(type1);//handler2 in type1
switch2(type2);//handler2 in type2
//意思也就是switch1和switch2并不用知道type到底是谁,只要type实现了各自需要的方法即可
//你那个业务就写成函数好了,然后可以在各自的类型中,根据业务的不同分别实现业务函数接口
//这些的最大好处在于,你某个type对与某个业务的处理变了,只需要在当前type下修改即可,不用污染其他type的代码
这个可以这么来,套用某大神的一句话,“抽取固定的,封装变化的”。
像这个type属于固定的,type对于不同业务的处理是变化的,所以你可以这么设计。
可能说的不对,大神轻喷。