一、代理模式
function Delegated(){//被委托方
this.job=function(){
alert("学习");
}
this.skill=function(){
alert("吃饭");
}
this.loan=function(){
alert("听音乐");
}
}
function Agent(){//代理方
this.job=function(){
alert("学习");
}
this.loan=function(){
alert("吃饭");
}
this.skill=function(){
alert("上班");
}
//以上是代理机构的特长;
/**
* 到这里代理方发现只缺教学的,代理方只是缺少一项:听音乐。所以代理被委托方的“听音乐”
*/
this.teach=new Delegated().loan;//合作成功
}
二、工厂模式
function Factory(color){//生产笔记本的流水线
return {
"screen":"this is screen",
"keybord":"this is keybord",
"mouse":"this is mouse",
"USB":"this is API of USB",
"storage":"this is storage",
"color":color
}
}
var _yellow=Factory("yellow");//来一个黄色的笔记本
var _black=Factory("black"); //来一个黑色的笔记本
var _purple=Factory("purple"); //来一个紫色的笔记本
三、抽象工厂
function AbstractFactory(){//工厂
return {
"thickness":"2mm",
"size":"5.8inch",
"material":"Diamonds"
}
}
function Iphone(){
this.shell="铝合金";
this.model="7Plus";
this.screen=AbstractFactory();
}
function Mate8(){
this.shell="铝合金";
this.model="Mate8";
this.screen=AbstractFactory();
}
function P9(){
this.shell="铝合金";
this.model="P9";
this.screen=AbstractFactory();
}
四、适配器模式
function Adapter(part){
switch(typeof part){
case "Number":
//number
break;
case "String":
//String
break;
case "Object":
//Object
break;
case "undefined":
//undefined
break;
}
}
五、单例模式
function Single(){
if(!Single.instance){
Single.instance={
"name":"tom"
}
}
return Single.instance;
}
var _obj1=Single();
_obj1.name="lily";
var _obj2=Single();
console.log(_obj2===_obj1);//true,多次获取相同对象的时候,操作对象是同一个
六、观察者模式
function Scan(obj){
Scan.prototype.card={
"number":"1120",
"type":"vip"
};
Scan.prototype.paper={
"content":"请你周六来消费",
"type":"A4paper"
}
for(var k in Scan.prototype){
obj[k]=Scan.prototype[k];
}
}
window.οnlοad=function(){
Scan(document.getElementsByTagName("div")[0]);
console.log(document.getElementsByTagName("div")[0].paper);//Object {content: "请你周六来消费", type: "A4paper"}
}