创建型设计模式
是一类处理对象创建的设计模式,通过某种方式控制对象的创建来避免基本对象创建时可能导致的设计上的问题或增加设计上的复杂度
Simpe Factory
简单工厂模式,又叫静态工厂方法,由一个工厂对象决定创建某一种产品对象类的实例,主要用于创建同一类对象
基础需求
let LoginAlert=function (text) {
this.content=text;
};
LoginAlert.prototype.show=function () {};
let userNameAlert=new LoginAlert('username <= 16 char number');
userNameAlert.show();
let passworldAlert=new LoginAlert('password error');
passworldAlert.show();
let LoginConfirm=function (text) {
this.content=text;
};
LoginConfirm.prototype.show=function () {};
let loginFailConfirm=new LoginConfirm('username dont exist');
loginFailConfirm.show();
let LoginPrompt=function (text) {
this.text=text;
};
LoginPrompt.prototype.show=function(){};
let PopFactory=function (name) {
switch (name){
case 'alert':
return new LoginAlert();
case 'confirm':
return new LoginConfirm();
case 'prompt':
return new LoginPrompt();
}
};
简单工厂
let Basketball=function () {
this.intro='basketball';
};
Basketball.prototype={
getMember:function () {
console.log('5 members');
},
getBallSize:function () {
console.log('very big');
}
};
let Football=function () {
this.intro='football';
};
Football.prototype={
getMember:function () {
console.log('11 members');
},
getBallSize:function () {
console.log('big');
}
};
let Tennis=function () {
this.intro='tennis';
};
Tennis.prototype={
getMember:function () {
console.log('1 members');
},
getBallSize:function () {
console.log('little');
}
};
let SportsFactory=function (name) {
switch (name){
case 'NBA':
return new Basketball();
case 'wordCup':
return new Football();
case 'FrenchOpen':
return new Tennis();
}
};
let footnall=SportsFactory('wordCup');
console.log(footnall);
console.log(footnall.intro);
footnall.getMember();
对象包装实现
function createBook(name,time,type) {
let o={};
o.name=name;
o.time=time;
o.type=type;
o.getName=function () {
console.log(this.name);
};
return o;
}
let book1=createBook('js book',2014,'js');
let book2=createBook('css book',2013,'css');
book1.getName();
book2.getName();
function createPop(type,text) {
let o={};
o.content=text;
o.show=function () {
console.log(this.content);
};
if (type === 'alert'){}
if (type === 'prompt'){}
if (type === 'confirm'){}
return o;
}
let userNameAlert=createPop('alert','26 char and number');
Factory Method
工厂方法模式,通过对产品类的抽象使其创建业务主要负责用于创建多类产品的实例
简单工厂实现(实现新的需求需要修改工厂类和添加类)
let Java=function (content) {
this.content=content;
(function (content) {
let div=document.createElement('div');
div.innerHTML=content;
div.style.color='green';
document.getElementById('container').appendChild(div);
})(content);
};
let Php=function (content) {
this.content=content;
(function (content) {
let div=document.createElement('div');
div.innerHTML=content;
div.style.color='yellow';
div.style.background='red';
document.getElementById('container').appendChild(div);
})(content);
};
let JavaScript=function (content) {
this.content=content;
(function (content) {
let div=document.createElement('div');
div.innerHTML=content;
div.style.color='pink';
document.getElementById('container').appendChild(div);
})(content);
};
function JobFactory(type,content) {
switch (type){
case 'java':
return new Java(content);
case 'php':
return new Php(content);
case 'JavaScript':
return new JavaScript(content);
}
}
let js=JobFactory('JavaScript','javascript.....');
忽略new
let Demo=function () {};
Demo.prototype={
show:function () {
console.log('success');
}
};
let d=new Demo();
d.show();
let d=Demo();
d.show();
安全模式类
let Demo=function () {
if (!(this instanceof Demo)){
return new Demo();
}
};
Demo.prototype={
show:function () {
console.log('success');
}
};
let d=Demo();
d.show();
安全工厂方法
let Factory=function (type, content) {
if (this instanceof Factory){
let s=new this[type](content);
return s;
} else {
return new Factory(type,content);
}
};
Factory.prototype={
Java:function (content) {},
JavaScript:function (content) {},
php:function (content) {},
UI:function (content) {
this.content=content;
(function (content) {
let div=document.createElement('div');
div.innerHTML=content;
div.style.border='1px solid red';
document.getElementById('container').appendChild(div);
})(content);
},
};
let data=[
{type:'JavaScript',content:'javascript'},
{type:'Java',content:'java'},
{type:'Php',content:'php'},
{type:'UI',content:'ui'},
{type:'UI',content:'ui'},
{type:'JavaScript',content:'javascript'},
{type:'JavaScript',content:'javascript'},
];
let obj=[];
for (let i = 6;i>=0;i--){
obj[i]=Factory(data[i].type,data[i].content);
console.log(obj[i]);
}
Abstract Factory
抽象工厂模式,通过对了的工厂抽象使其业务用于对产品类簇的创建,而不负责创建某一类的产品的实例
抽象类,一种声明但不能使用的类,但是使用就会报错
let Car=function () {};
Car.prototype={
getPrice(){
return new Error('cant call');
}
getSpeed(){
return new Error('cant call');
}
};
抽象工厂模式,一般用作父类创建子类
let VehicleFactory=function (subType, superType) {
if (typeof VehicleFactory[superType]==='function'){
function F() {}
F.prototype=new VehicleFactory[superType]();
subType.constructor=subType;
subType.prototype=new F();
} else {
throw new Error('dont create abc');
}
};
VehicleFactory.Car=function () {
this.type='car';
};
VehicleFactory.Car.prototype={
getPrice(){
return new Error('cant call');
},
getSpeed(){
return new Error('cant call');
}
};
VehicleFactory.Bus=function () {
this.type='bus';
};
VehicleFactory.Bus.prototype={
getPrice(){
return new Error('cant call');
},
getPassengerNum(){
return new Error('cant call');
}
};
VehicleFactory.Truck=function () {
this.type='truck';
};
VehicleFactory.Truck.prototype={
getPrice(){
return new Error('cant call');
},
getTrainload(){
return new Error('cant call');
}
};
抽象与实现
let BMW=function (price, speed) {
this.price=price;
this.speed=speed;
};
VehicleFactory(BMW,'Car');
BMW.prototype.getPrice=function () {
return this.price;
};
BMW.prototype.getSpeed=function () {
return this.speed;
};
let Lamborghini=function (price, speed) {
this.price=price;
this.speed=speed;
};
VehicleFactory(Lamborghini,'Car');
Lamborghini.prototype.getPrice=function () {
return this.price;
};
Lamborghini.prototype.getSpeed=function () {
return this.speed;
};
let YUTONG=function (price, passenger) {
this.price=price;
this.passenger=passenger;
};
VehicleFactory(YUTONG,'Bus');
YUTONG.prototype.getPrice=function () {
return this.price;
};
YUTONG.prototype.getPassengerNum=function () {
return this.passenger;
};
let BenzTruck=function (price, trainLoad) {
this.price=price;
this.trainLoad=trainLoad;
};
VehicleFactory(BenzTruck,'Truck');
BenzTruck.prototype.getPrice=function () {
return this.price;
};
BenzTruck.prototype.getTrainLoad=function () {
return this.trainLoad;
};
let truck=new BenzTruck(1000000,1000);
console.log(truck.getPrice());
console.log(truck.type);
Builder
建造者模式,将一个复杂对象的构建层与其表现层相互分离,同样的构建过程可采取不同的表示,本质就是复合对象
let Human = function (param) {
this.skill = param && param.skill || 'serect';
this.hobby = param && param.skill || 'serect';
};
Human.prototype = {
getSkill() {
return this.skill;
},
getHobby() {
return this.hobby;
}
};
let Named = function (name) {
let that = this;
(function (name, that) {
that.wholeName = name;
if (name.indexOf(' ') > -1) {
that.firstName = name.slice(0, name.indexOf(' '));
that.secondName = name.slice(name.indexOf(' '));
}
})(name, that);
};
let Work = function (work) {
let that = this;
(function (work, that) {
switch (work) {
case 'code':
that.work = 'enginer';
that.workDescrit = 'fouce on coding';
break;
case 'UI':
case 'UE':
that.work='desginer';
that.workDescrit='desgin more than art';
break;
case 'teach':
that.work = 'teacher';
that.workDescrit = 'on teach';
break;
default :
that.work = work;
that.workDescrit = 'sorry dont konw';
}
})(work,that);
};
Work.prototype.changeWork=function (work) {
this.work=work;
};
Work.prototype.changeDescript=function (setence) {
this.workDescrit=setence;
};
let Person=function (name, work) {
let _person=new Human();
_person.name=new Named(name);
_person.work=new Work(work);
return _person;
};
let person=new Person('xiao ming','code');
console.log(person.skill,person.name.firstName,person.work.work,person.work.workDescrit);
person.work.changeDescript('change');
console.log(person.work.workDescrit);
Prototype
原型模式,用原型实例指向创建对象的类,使用于创建新的对象的类共享原型对象的属性和方法
let LoopImages=function (imgArr,container) {
this.imageArray=imgArr;
this.container=container;
this.createImage=function () {};
this.changeImage=function () {};
};
let SlideLoopImg=function (imgArr,container) {
LoopImages.call(this,imgArr,container);
this.changeImage=function () {
console.log('SlideLoopImg changeImage function');
};
};
let FadeLoopImg=function (imgArr, container, arrow) {
LoopImages.call(this,imgArr,container);
this.arrow=arrow;
this.changeImage=function () {
console.log('FadeLoopImg changeImage function');
};
};
let fadeImg=new FadeLoopImg(['01.jpg','02.jpg','03.jpg','04.jpg'],'slide',['left.jpg','right.jpg']);
fadeImg.changeImage();
修改
let LoopImages=function (imgArr,container) {
this.imageArray=imgArr;
this.container=container;
};
LoopImages.prototype={
createImage:function () {
console.log('LoopImages createImage function');
},
changeImage:function () {
console.log('LoopImages changeImage function');
},
getImageLength:function () {
return this.imageArray.length;
}
};
let SlideLoopImg=function (imgArr,container) {
LoopImages.call(this,imgArr,container);
};
SlideLoopImg.prototype=new LoopImages();
SlideLoopImg.prototype.changeImage=function () {
console.log('SlideLoopImg changeImage function');
};
let FadeLoopImg=function (imgArr, container, arrow) {
LoopImages.call(this,imgArr,container);
this.arrow=arrow;
};
FadeLoopImg.prototype=new LoopImages();
FadeLoopImg.prototype.changeImage=function () {
console.log('FadeLoopImg changeImage function');
};
FadeLoopImg.prototype.getContainer=function(){
return this.container;
};
let fadeImg=new FadeLoopImg(['01.jpg','02.jpg','03.jpg','04.jpg'],'slide',['left.jpg','right.jpg']);
console.log(fadeImg.container,fadeImg.getImageLength(),fadeImg.getContainer());
fadeImg.changeImage();
原型继承
function prototypeExtend() {
let F=function () {},
i=0,
args=arguments,
len=args.length;
for (;i<len;i++){
for (let j in args[i]){
F.prototype[j]=args[i][j];
}
}
return new F();
}
let penguin=prototypeExtend({
speed:20,
swim:function () {
console.log('speed '+this.speed);
}
},{
run:function (speed) {
console.log('run speed '+speed);
}
},{
jump:function () {
console.log('jump');
}
});
penguin.swim();
penguin.run(10);
penguin.jump();
Singleton
单列模式,又称单体模式,是只允许实例化一次的对象类,有时也用一个对象来规划一个命名空间,管理对象上的方法和属性
function g(id) {
return document.getElementById(id);
}
function css(id,key,value) {
g(id).style[key]=value;
}
function attr(id, key, value) {
g(id)[key]=value;
}
function html(id, value) {
g(id).innerHTML=value;
}
function on(id, type, fn) {
g(id)['on'+type]=fn;
}
单列模式实现
let Mar={
g:function g(id) {
return document.getElementById(id);
},
css:function css(id,key,value) {
this.g(id).style[key]=value;
},
};
小型代码库
let A={
Util:{
util_method1:function () {},
util_method2:function () {
console.log('haha');
},
},
Tool:{
tool_method1:function () {
console.log('lololo');
},
tool_method2:function () {}
},
Ajax:{
get:function () {
console.log('what fuck');
},
post:function () {}
},
others:{}
};
A.Util.util_method2();
A.Tool.tool_method1();
A.Ajax.get();
无法修改的静态变量,静态变量大写
let Conf=(function () {
let conf={
MAX_NUM:100,
MIN_NUM:1,
COUNT:1000
};
return {
get:function (name) {
return conf[name]?conf[name]:null;
}
};
})();
let count=Conf.get('COUNT');
console.log(count);
惰性单例,有时单例对象需要延迟创建
let LazySingle=(function () {
let _instance=null;
function Single() {
return {
publicMethod:function () {},
publicProperty:'1.0'
}
}
return function () {
if (!_instance){
_instance=Single();
}
return _instance;
}
})();
console.log(LazySingle().publicProperty);