软件工程系的学生不会设计模式,真丢人(´ཀ`」 ∠)
Module 模块模式
var testMoudle = (function (){
var counter = 0;
return {
incrementCounter:function(){
return ++ counter;
},
resetCounter:function(){
console.log("counter value prior to reset: " + counter);
counter = 0;
}
}
})();
testMoudle.incrementCounter();
testMoudle.resetCounter();
通过立即执行函数,返回一个对象字面量构建的对象。这种方式可以让对象方法以及属性在全局上下文中隔离出来,不污染全局作用域。
var myRevealingModule = function(){
var privateVar = "Ban Cherry",
publicVar = " Hey there";
function privateFunction(){
console.log("Name:" + privateVar);
}
function publicSetName(atrName){
privateName = strName;
}
function publicGetName(){
privateFunction();
}
return {
setName:publicSetName,
greeting:publicVar,
getName:publicGetName
}
}();
单例模式
var mySingletion = (function(){
var instance;
function init(){
function privateMethod(){
console.log("I am private");
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
publicMethod:function(){
console.log("The public can see me!");
},
publicProperty: "I am also public",
getRandomNumber:function(){
return privateRandomNumber;
}
}
}
return{
getInstance:function(){
if(!instance){
instance = init();
}
return instance;
}
}
})();
var singleA = mySingletion.getInstance();
var singleB = mySingletion.getInstance();
singleA.publicMethod();
console.log(singleA.getRandomNumber())
console.log(singleB.getRandomNumber())
console.log(singleA === singleB)
单例模式在技术实现上其实只是对模块模式进行了一个再处理,通过监控一个flag来控制是否执行init函数进行类的实例化
观察者模式
观察者模式的核心对象有订阅通知等若干方法,技术实现上为操作一个绑定在其原型链上的数组,并且维护一系列相关的操作函数.
中介者模式
没错,是坑 ( 'ω')