开闭原则,如果jQuery源码稍微了解,肯定知道它的应用了.
一个模块----函数或对象,应该凭着经验来判断, 对扩展开放,对修改关闭.------
一般用继承实现扩展,用闭包来实现关闭.
为什么开闭原则?它跟复杂度有什么关系,?
复杂度,就是一个函数里包含的功能个数;当开闭原则不遵守时,想扩展功能,必然去原来的函数里添加代码,导致原来的函数功能增加.
里氏代换原则:是对开闭原则的补充,子类可以扩展父类,但不可改变父类.
function changFangxing(height,width){
this.width = 0;
this.height = 0;
this.setWidth = function(width){
this.width = width;
};
this.setHeight = function(height){
this.height = height
}
this.getWidth = function (){
return this.width
}
this.getHeight = function(){
return this.height
}
}
zhengfangxing.prototype = new changFangxing();
function zhengfangxing(){
this.setHeight = function(height){
this.width = height;
this.height = height;
}
this.setWidth = function(width){
this.setHeight(width)
}
}
function resetSize(o){
while(o.getHeight() < o.getWidth()){
o.setHeight(o.getWidth + 1)
}
console.log(‘over‘)
}
var oCh = new changFangxing(100,200);
resetSize(oCh)
var oZh = new zhengfangxing()
oZh.setHeight(100)
resetSize(oZh)//会是死循环
原文地址:https://www.cnblogs.com/dangdanghepingping/p/10121783.html