开放封闭原则之模式的黄金法则

开放-封闭原则应该算是这几个原则里面最容易理解的一个。它的宗旨就是:
若是你想扩展或者改变一个程序的功能,能够增长代码,可是不能改变程序的源码。
若是,是对于那些码农来讲,最快捷的办法就是改变源码,可是咱们面向的是更复杂的项目,咱们的目的不是当码农,而是要作一名代码艺术家,想完成一件艺术品同样去完成咱们的项目。
拿装饰者模式的例子来讲吧。 若是咱们想改变onload的函数,即,其余小伙伴,有可能已经在onload上面绑定好,咱们能够翻阅onload代码,进行修改。 可是,这个扩展性简直啦!!!
从装饰者模式能够知道,咱们可使用引用装饰进行改动。ajax

var fn = window.onload;
var change = function(){
    fn();
    conosle.log("整洁代码");
}
window.onload = function(){  
    change();
}

固然,咱们也可使用AOP,进行一个装饰,将原来代码实现的功能彻底保留,只在外部添加一些代码。
另外,if语句就是开放封闭原则的死敌.
这个是状态模式中的一个例子。函数

if(state === "auto"){
            console.log("制热");
            state = "hot";
        }else if(state === "hot"){
            console.log("制冷");
            state = "cold";
        }else if(state === "cold"){
            console.log("送风");
            state = "wind";
        }else if(state === "wind"){
            console.log("除湿");
            state = "dry";
        }else if(state === "dry"){
            console.log("自动");
            state = "auto";
        }

能够从上面的代码看出,若是功能继续发生变化,你必须作的就是改动原来代码的内容,这是极不可取的。 因此依照开放封闭原则,咱们须要进行优化,能够修改成这样优化

//定义状态
var Auto= function(button){
    this.turn = button;
}
Auto.prototype.press= function(){
    console.log('制热');
    this.turn.setState("hot");
}
var Hot = function(button){
    this.turn = button;
}
Hot.prototype.press= function(){
    console.log('制冷');
    this.turn.setState("cold");
}
var Cold = function(button){
    this.turn = button;
}
Cold.prototype.press= function(){
    console.log('送风');
    this.turn.setState("wind");
}
var Wind = function(button){
    this.turn = button;
}
Wind.prototype.press= function(){
    console.log('除湿');
    this.turn.setState("dry");
}
var Dry = function(button){
    this.turn = button;
}
Dry.prototype.press= function(){
    console.log('自动');
    this.turn.setState("auto");
}
//定义状态仓库
var Remoter = function(){
    this.auto = new Auto(this);
    this.hot = new Hot(this);
    this.cold = new Cold(this);
    this.wind = new Wind(this);
    this.dry = new Dry(this);
    this.state = "auto";
}
Remoter.prototype.setState = function(state){
    this.state=state;
}
Remoter.prototype.press = function(){
    this[this.state].press();  //执行对应状态的press
}
Remoter.prototype.init = function(){  //定义执行者
    document.querySelector('.switch').addEventListener("click",()=>{
        this.press();
    },false);
}
new Remoter.init();  //初始化

即,使用对象的多态性,消除条件分支语句。this

处理开放封闭模式的特例

咱们都是人,不可能一开始都写出完美的代码。但咱们在写程序的时候,要永远的给本身留一手,以便后面改动的须要。 在模板模式里,咱们给特殊性留了一条后路, 咱们使用钩子方法,经过外部的设置,咱们能够获得不用的结果。
固然,咱们还可使用callback函数,执行本身想要作的功能,好比在$.ajax调用的时候,咱们添加回调函数,执行本身想要的函数功能,这些都是很棒的实现开放封闭模式原则的办法。prototype

最后一点

这里想说的就是,原则是一份指导,可以指引你的代码结果怎样作,能够达到最优的形式,但,事实上,咱们遵不遵照,是彻底取决于我的而言的。 并且,有时候咱们写程序,真的没必要过度追求设计,由于咱们是完成用户的交付的需求,若是一味追求设计,无疑增长代码的难度,和实现的时间。因此,一切跟着感受走,咱们写程序不也是凭感受写的吗?设计

相关文章
相关标签/搜索