js-面向对象-设计模式-工厂模式

工厂函数能够创建对象,并且函数是()执行不是new执行。

简单工厂模式

    function createStudents(name,age,sex) {
        return {
            name : name,
            age : age,
            sex : sex,
            study : function () {
                console.log("语数英理化生")
            }
        }
    }
    var xiaoming = createStudents("小明",20,"男")
    console.log(xiaoming)

简单工厂模式不能 使用instanceof,因为不是new执行的

一般工厂模式

function Car(color,doors) {
        this.color = color;
        this.doors = doors;
        console.log("这是一辆"+this.color+"色的卡车,它有"+this.doors+"扇门");
    }
     function createFactory(color,doors) {
         return new Car(color,doors);
     }
     var car1 = new createFactory("白",4);
     var car2 = new createFactory("黑",2);
     console.log(car1 instanceof Car);//true

这里感觉是多此一举,但是工厂模式是面向接口编程。

简单工厂模式

 function Car(color,doors) {
        this.color = color;
        this.doors = doors;
        console.log("这是一辆"+this.color+"色的卡车,它有"+this.doors+"扇门");

        //这里需要retur自己出去,因为工厂函里是  Car 圆括号直接执行,不是new 执行 不会自动return
        return this;
    }
    function Suv(seat) {
        this.seat = seat;
        console.log("这是一辆"+this.seat+"座的SUV")
        return this;
    }
    function Bus(position,fullLoad) {
        this.position = position;
        this.fullLoad=fullLoad;
        console.log("这是一辆"+this.position+"的公交车,满座人数是"+this.fullLoad+"人");
        return this;
    }
     function createFactory(type) {
         //通过type判断,如果是Car则创建 car 如果是Suv 则创建SUV............
         if(type == "Car"){
             //apply  指定执行上下文
             return Car.apply(new Car(),[].slice.call(arguments,1));
         }
         if(type == "Suv"){
             return Suv.apply(new Suv(),[].slice.call(arguments,1))
         }if(type == "Bus"){
             return Bus.apply(new Bus(), [].slice.call(arguments,1))
         }
     }
     var car = new createFactory("Car","白",4);
     var suv = new createFactory("Suv",7);
     var suv = new createFactory("Bus","北京",55);
     console.log(car instanceof Car);//true
     console.log(car instanceof createFactory);//false

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值