javascript設計模式

面向對象編程

1.創建,使用函數

var CheckObject = {

checkName : function() {}

}

創建,使用類(原型,鏈式)

var CheckObject = function() {

this.checkName = fucntion(){}

}

var a = new CheckObject();

a.checkName();

var CheckObject = function(){};

CheckObject.prototype = {

checkName:function(){}

}

var a = new CheckObject();

a.checkName();

var CheckObject = function(){};

CheckObject.prototype = {

checkName:function(){

return this;

}

}

var a = new CheckObject();

a.checkName();

Function.prototype.addMethod = function(name,fn){

this[name] = fn;

}

var CheckObject = new Function();

CheckObject.addMethod('checkName',function(){});

CheckObject.checkName();

Function.prototype.addMethod = function(name,fn){

this[name] = fn;

return this;

}

var CheckObject = new Function();

CheckObject.addMethod('checkName',function(){});

CheckObject.checkName();

Function.prototype.addMethod = function(name,fn){

this[name] = fn;

return this;

}

var CheckObject = new Function();

CheckObject.addMethod('checkName',function(){

return this;

});

CheckObject.checkName();

Function.prototype.addMethod = function(name,fn){

this.ptototype[name] = fn;

return this;

}

var CheckObject = new Function();

CheckObject.addMethod('checkName',function(){

return this;

});

var a = new CheckObject();

a.checkName();

2.私有屬性方法

公有屬性方法(特權方法,構造器) this.?

類靜態私有屬性方法

類靜態公有屬性方法 prototype.

var Book = function(){

var name=1;//私有

this.getName = function(){};//公有,特權,構造器

}

Book.bookNum = 0;//靜態私有

Book.prototype = {

isJSBook : false//靜態公有

}


var Book = (function(){

var bookNum = 0; //靜態私有

function _book(){

var name; //私有

this.getName = function(){}; //公有,特權,構造器

}

_book.prototype = {

isJSBook :false // 靜態公有

}

return _book;

})();

繼承

//類式繼承

function SuperClass(){}

SuperClass.prototype.get = function(){};

function SubClass(){}

SubClass.prototype = new SuperClass();

SubClass.prototype.getSub = function(){};

var a = new SubClass();

a.get();

a.getSub();

//構造函數式繼承

function SuperClass(){}

SuperClass.prototype.show(){};

function SubClass(){

SuperClass.call(this);

}

var a= new SubClass();

a.show();// 錯誤用法

//組合式繼承

function SuperClass(){}

SuperClass.prototype,get=function(){};

function SubClass(){

SuperClass.call(this)

}

SubClass.protorype = new SuperClass();

SubClass.prototype.getSub = function(){};

var a = new SubClass();

a.get();

a.getSub();

//原型式繼承

function inheritObject(o){

function F(){}

F.prototype = o;

return new F();

}

var book = {};

var newBook = inheritObject(book);

newBook.xxx;

//寄生式繼承

function createBook(obj){

var o = new inheritObject(obj);

o.get = function(){};

return o;

}

var book = {};

var newBook = createBook(book);

newBook.xxx;


//寄生組合式繼承

function inheritPrototype(subClass,superClass){

var p = inheritObject(superClass.prototype);

p.constructor = subClass;

subClass.prototype = p;

}

var SuperClass= {};

SuperClass.prototype.get= fucntion(){};

var SubClass(){

SuperClass.call(this);

};

inheritPrototype(SubClass,SuperClass);

SubClass.prototype.getSub = fucntion(){};

var a= new SubClass();

a.xxx;


創建型設計模式:處理對象創建

3.簡單工廠模式

//先定義類,然后用函數返回一個類的實例對象

var PopFactory = function(name){

switch(name){

case 'alert':return newLoginAlert();

}

}

var userNameAlert=PopFactory ('alert');

//用函數返回一個對象

function createPop(type,text){

var o=new Object();

o.content = type;

o.show = function(){};

if(type === 'alert'){}

return o;

}

var userNameAlert = createPop('alert','xxx');

4.工廠方法模式

//在函數的屬性里定義類,然后用函數返回一個類的實例對象

var Factory = function(type,content){

if(this instanceof Factory){

var s= new this[type](content);

return s;

}else{

return new Factory(type,content);

}

}

Factory.prototype={

Java:fucntion(){}

}

5.抽象工廠模式

//在函數的屬性里定義抽象類,然后用函數返回一個抽象類的子類,然后用子類創建實例對象

var VeicleFactory = 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('未創建該抽象類');

}

}

VhicleFactory.Car = function(){

this.type ='car';

}

VhicleFactory.Car.prototype = {

getPrice:function(){}

}

var BMW = function(price){

this.price =price;

}

VhicleFactory(BMW,'Car');

BMW.prototype.getPrice = function(){

return this.price;

}

var car = new BMW(1000);

car.getPrice();

car.type;

6.建造者模式

//用函數返回一個實例化對象,該實例化對象的某些屬性是其他類的實例對象

var Human = fucntion(){};

Human.prototype={};

var Name = fucntion(name){};

var Work = function(work){};

Work.prototype=fucntion(){};

var Person = function(name,work){

var _person = new Human();

_person.name = new Name(name);

_person.work =new ?Work(work);

return _person;

}

var person = new Person('xxx','xxx');

7.原型模式

//先創建父類,再創建子類,最后通過子類創建實例對象

var LoopImages=function(){};

LoopImages.prototype={};

var FadeLoopImg = function(){

LoopImages.call(this);
}

FadeLoopImg.prototype = new LoopImages();

var fadeImg = new FadeLoopImg();

//原型繼承,創建一個對象,該對象的原型復制其他屬性

var prototypeExtend(){

var F = function(),args=arguments,i=0,len=args.length;

for(;i<len;i++){

for(var j in args[i]){

F.prototype[j]=args[i][j];

}

}

return new F();

}

var penguin = prototypeExtend({xxx});

penguin.xxx;

8.單例模式

//用對象收編函數,此對象相當于命名空間

//單例模式還可以用來創建小型代碼庫,靜態變量,惰性單例

var Ming = {

g:function(){}

}


結構型設計模式:如何將類或對象組合成更大更復雜的結構

9.外觀模式

//兼容處理

function addEvent(dom,type,fn){

if(dom.addEventListener){

dom.addEventListener(type,fn,false);

}else if(dom.attachEvent){

dom.attachEvent('on'+type,fn);

}else{

dom['on'+type]=fn;

}

}

addEvent(xxx,'click',function(){});

10.適配器模式

//把舊框架的方法用新框架重寫

A.g=function(id){

return $(id).get(0);

}

//適配多個參數

function doSomeThing(obj){

var _adapter = {

name:'xxx'

}

for(var i in _adapter){

_adapter[i] = obj[i] || _adapter[i];

}

}

//數據適配

var arr = ['js','book','前端','8月1日'];

function arrToObjAdapter(arr){

return{

name:arr[0],

type:arr[1],

title:arr[2],

data:arr[3]

}

}

var arrToObjAdapter(arr);

//服務器端數據適配

function ajaxAdapter(data){

return [data[key1],data[key2]]

}

11.代理模式

//統計代理

car Count = (fucntion(){

var _img = new Image();

return function(param){

var str = 'http://www.count.com/a.gif?';

for(var i in param){

str+=i+'='+param[i];

}

_img.src = src

}

})()

Count({num:10})

//jsonp

<script type="text/JavaScript">

function jsonpCallBack(res,rep){}

</script>

<script type="text/JavaScript" src="http://localhost/test/jsonp.php?callback=jsonpCallBack&data=getJsonData">

<?php

$data = $_GET['data'];

$callback = $GET['callback'];

echo $callback."('success','".$data."')";

?>

12.裝飾者模式

var decorator = function(input,fn){

var input = document.getElementById(input);

if(typeof input.onclick === 'function'){

var oldClickFn = input.onclick;

input.onclick = function(){

olc=dClickFn;

fn();

}

}else{

input.onclick = fn;

}

}

13.橋接模式

//分離事件與UI

fucntion changeColor(dom,color){

dom.style.color = color;

}

var spans = document.getElementByTagName('span');

spans[0].onMouseover = function(){

changeColor(this,'red');

}

14.組合模式

//抽象類

var News = function(){

this.children = [];

this.element = null;

}

New.prototype = {

init:function(){

throw new Error(‘請重寫你的方法’);

}

}

//類簇1

var Container = function(id,parent){

New.call(this);

this.id = id;

this.init();

}

inhertPrototype(Container,News);

Container.prototype.init = function(){}

//類簇2

var ImageNews= function(clasname){

New.call(this);

this.init();

}

inhertPrototype(ImageNews,News);

ImageNews.prototype.init=function(){}

//實例對象

var news1 = new Container('news');

news1.add(

new Item('normal').add(

new ImageNews('xxx')

)

)

15.享元模式

//翻頁時改變dom內容

var FlyWeight = function(){

var created = [];

function(){

var dom = document.createElement('div');

document.getElementById('container').appendChild(dom);

created.push(dom);

return dom;

}

return{

getDiv:function(){

if(created.length <5){

return create();

}else{

var div = created.shift();

created.push(div);

return div;

}

}

}

}


行為型設計模式:不同對象之間職責劃分或算法抽象

16.模板方法模式

//父類

var Alert = function(){}

Alert.prototype={}

//子類

var RightAlert = function(){

Alert.call(this);

}

RightAlert.prototype = new Alert();

new RightAlert().init();

17.觀察者模式

var Observer = (function(){

var _message={};

return {

regist:function(type,fn){

if(typeof _messages[type] === 'undefined'){

_messages[type] = [fn];

}else{

_messages[type].push(

}

},

fire:function(){

if(!_messages[type])

return;

var events = {

type:type,

args:args||{}

},

i=0,

len = _messages[type].length;

for(;i<len;i++){

_messages[type][i].call(this,events);

}

},

remove:function(){

if(_meassages[type] instanceof Array){

var i = _messages[type].length -1;

for(;i>=0;i--){

_messages[type][i] ===fn && _messsages[type].splice(i,1);

}

}

}

}

})();


var Student = function(result){

var that = this;

that.say = function(){}

};

Student.prototype.answer = function(question){

Observer.register(question,this,say);

}

Student.prototype.sleep = function(){

Observer.remove(question,this.say);

}

var Teacher = function(){};

Teacher.prototype.ask=function(){

Obeserve.fire(question);

}

var student1 = new Student(),student1 = new Student(),student1 = new Student();

student1.answer('問題1');

student1.answer('問題2');

student2.answer('問題1');

student3.answer('問題1');

student3.answer('問題2');

student1.sleep('問題2');

var teacher = new Teacher();

teacher.ask('問題1');

teacher.ask('問題2');

18.狀態模式

var ResultState = function(){

var States = {

state0:function(){}

}

function show(result){

States['state'+result]&&State['state'+result]();

}

return {

show:show

}

}

19.策略模式

var PriceStrategy = function(){

var stragtery = {

return30:function(price){}

}

return function(algorithm,price){

return stragtegy[algorithm]&&stragtegy[algorithm](price);

}

}();

var price=PriceStrategy('return30','312');

20.職責鏈模式

請求模塊,響應數據適配模塊,創建組件模塊單元測試

21.命令模式

var viewCommand = (function(){

//模板類型

var tpl={

product:[

'<p>{#text#}</p>'

].join(''),

title:[].join()

},

html = '';

function formateString(str,obj){

return str.replace(/\{#(\w+)#\}/g),function(match,key){

return obj[key];

})

}

var Action = {

create:function(data,view){

if(data.length){

for(var i =0,len=data.length;i<len;i++){

html+=formateString(tpl[view],data[i]);

}else{

html+=formatString(tpl[view],data);

}

}

},

display:function(container,data,view){

if(data){

this.create(data,view);

}

document.getElementById(container).innerHTML = html;

html='';

}

}

return function excute(){

msg.param = Object.prototype.toString.call(msg.param) === "[objectArray]"?msg.param:[msg.param];

Action[msg.command].apply(Action,msg.param);

}

})();

viewCommand({command:'display',param:{'title',titleData,'title'}});


22.訪問者模式

function bindIEEvent(dom,type,fn,data){

var data =data||{};

dom.attachEvent('on'+type,function(e){

fn.call(dom,e,data);

})

}

23.中介者模式

var mediator = function(){

var _msg = {};

return {

register:function(type,action){

if(!_msg[type]){

_msg[type] = {};

}

_msg[type].push(action);

},

send:function(){

if(_msg[type]){

for(var i=0,len=_msg[type].length;i<len;i++){

_msg[type][i]&&_msg[type][i]();

}

}

}

}

}();

24.備忘錄模式

var ?Page = function(){

var cache ={};

return function(page,fn){

if(!cache[page]){

$.post('xxx',{page:page},function(res){

if(res.errNo == 0){

cache[page] = res.data;

}

showPage(page,res.data);

fn&&fn();

})

}

}

}

25.迭代器模式

var Iterator = function(items,container){

var container = container && document.getElementsByTagName(container) || document;

items = container.getElementsByTagName(items),

length = items.length,

index = 0,

splice = [].splice;

return{

first:function(){

index = 0;

rerurn items[index];

},

second:fucntion(){

index = items.length -1;

rerurn items[index];

},

pre:fucntion(){

if(--index >0){

return items[index]

}else{

index = 0;

rerurn null;

}

},

next:function(){

if(++index > length){

return items[index];

}else{

index = length -1;

return null;

}

},

get:function(num){

index = num >=0?num%length:num%length +length;

rerurn items[index];

},

dealEach:function(fn){

var args = splice.call(arguments,1);

for(var i=0;i<lengthl;i++){

fn.apply(items[i],args);

}

},

dealItem:fucntion(num,fn){

fn.apply(this.get(num),splice.call(arguments,2));

},

exclusive:function(num,allFn,numFn){

this.dealEach(allFn);

if(Object.prototype.toString.call(num) === "[Object Array]"){

for(var i=0,len = num.length;i<len;i++){

this.getItem(num[i],numFn);

}

}else{

this.getItem(num[i],numFn);

}

}

}

}

//數組迭代器,對象迭代器

//同步變量迭代取值器

var AGetter = function(key){

if(!A){

return undefined;

}

var result = A;

key = key.split(.);

for(var i = 0;,len=key.length;i<len;i++){

if(result[key[i]] !== undefined){

result = result[key[i]]

}else{

return undefined;

}

}

return result;

}

//同步變量迭代賦值器

var Asetter = function(key,val){

if(!A)

return false;

var result = A;

key = key.split('.');

for(var i =0,len=key.length;i<len-1;i++){

if(result[key[i]] === undefined){

result[key[i]] = {};

}

if(!(resultp[key[i]] instanceof Object)){

throw new Error('A.'+key.splice(0,i+1).join('.')+'is not Object');

return false;

}

return result[key[i]];

}

return result[key[i]]= val;

}

// 分支循環嵌套問題

function dealImage(){

var Deal = function(){

var method = {

'red':function(){}

}

return function(type){

return method[type];

}();

function eachData(fn){

for(var i=0,len=data.length;i<len;i+=4){

fn(i);

}

}

}

}

26.解釋器模式

算法

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容