面向对象编程的几种常见设计模式

<script>
//前言:由同一个构造函数创造出来的多个对象,会有不同的地址,所以不会是相等的。
//单例模式:确保某个类(构造函数)只有一个实例,且自行实例化并向整个系统提供这个实例。

    function Bar(){
        if(!Bar.inst){   //判断是不是已经存在这个实例
            Bar.inst = {
                name : 'hello'
            }
        }
        return Bar.inst;
    }
    var obj1= new Bar();
    var obj2= new Bar();
    console.log(obj1==obj2); //true,此时obj1和obj2都地址和内容都是相同的
</script>

<script>
//工厂模式:提供一个创建一系列相关对象的入口,统一对象创建职责创建对象时无需关心具体类。$()就是工厂模式
//*简单工厂模式:*
function Foo(){
    this.name = "I'm Foo"
};
function Bar(){
    this.name = "I'm Bar"
}
function fartory(arg){
    var result;
    if(arg=="foo"){
        return result=new Foo();
    }else if(arg=="bar"){
        return result=new Bar();
    }
    return result;
}
var obj= factory('bar');


----------
//*工厂模式:*
function Foo(){
    this.name = "I'm Foo"
};
function Bar(){
    this.name = "I'm Bar"
}
function Factory(){};  //工厂模式和简单工厂模式的区别是使用‘工厂类’进行创建
Factory.prototype.create=function(arg){
    var result;
    if(arg=='foo'){
        return result = new Foo();
    }else if(arg=='bar'){
        return result = new Bar();
    }
    return result
};
var fa = new Factory();
var obj = fa.create('foo);
console.log(obj.name)
</script>
<script>
//外观模式:定义一个高层接口,把子类集合在一起,方便调用。
function Foo(){}
function Bar(){}
function Baz(){}
function facade(){
    var obj1= new Foo();
    var obj1= new Bar();
    var obj1= new Baz();
}
new facade();
// *之前写的实现拖拽功能的就是外观模式。*
</script>
<script>
//适配器模式:将一个类的接口转换成客户希望的另一个接口,
//使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
 function Adapter(class1,method){  //适配器方法
     return class1.prototype[method]
 }
function Foo(){
   this.show = Adapter(Bar,'show')  //调用适配器,this.show优先级高于prototype.show
}
Foo.prototype.show = function(){  //没有适配就使用原型里的show
   console.log("两项插头")
 }
function Bar(){

}
Bar.prototype.show = function(){
    console.log("三项插头")
}
var obj = new Foo();
obj.show();
</script>

猜你喜欢

转载自blog.csdn.net/qq_33325959/article/details/79564726