开放封闭原则(OCP):软件实体(类、模块、函数)等应该是可以扩展的,但是不可修改。 即当需要改变一个程序的功能或者给这个程序增加新功能的时候,可以使用增加代码的方式,但是不允许改动程序的源代码
编写遵守开放-封闭原则的代码方式:
- 对象的多态
- 钩子:返回结果决定了程序的下一步走向(模板方法模式)
- 回调函数:回调函数是一种特殊的挂钩(AJAX的回调函数)
- 不符合OCP
var makeSound = function( animal ){
if ( animal instanceof Duck ){
console.log( '嘎嘎嘎' );
} else if ( animal instanceof Chicken ) {
console.log( '咯咯咯' );
}
};
var Duck = function(){};
var Chicken = function(){};
makeSound( new Duck() );
makeSound( new Chicken() );
//动物世界里增加一只狗之后,makeSound 函数必须改成:
var makeSound = function( animal ){
if ( animal instanceof Duck ){
console.log( '嘎嘎嘎' );
} else if ( animal instanceof Chicken ) {
console.log( '咯咯咯' );
} else if ( animal instanceof Dog ) {
console.log('汪汪汪' );
}
};
var Dog = function(){};
// 增加跟狗叫声相关的代码
makeSound( new Dog() ); // 增加一只狗
- 符合OCP(利用对象的多态)
var makeSound = function( animal ){
animal.sound();
};
var Duck = function(){};
Duck.prototype.sound = function(){
console.log( '嘎嘎嘎' );
};
var Chicken = function(){};
Chicken.prototype.sound = function(){
console.log( '咯咯咯' );
};
makeSound( new Duck() ); // 嘎嘎嘎
makeSound( new Chicken() ); // 咯咯咯
/********* 增加动物狗,不用改动原有的 makeSound 函数 ****************/
var Dog = function(){}; Dog.prototype.sound = function(){
console.log( '汪汪汪' ); };
makeSound( new Dog() ); // 汪汪汪
function getA(fn) {
console.log(1)
if (fn()) {
console.log(2)
}
}
getA(function() {
return true
})