js设计模式----创建者模式(1)抽象工厂模式

1)抽象工厂模式
JavaScript 的动态性质 排除了描述类的需要接口。
这里写图片描述
Instead of interfaces, JavaScript trusts that the class you provide implements all the
appropriate methods. At runtime the interpreter will attempt to call the method you
request and, if it is found, call it. The interpreter simply assumes that if your class
implements the method then it is that class. This is known as duck typing.

用冰火里面的国王,国王之手,兰尼斯特家族,塔格里安家族 ,来说明
首先implement一个的King class,这是一个具体的类包含实现的具体细节

let KingJoffery =(function () {
    function KingJoffery() {
  }
    KingJoffery.prototype.makeDecision = function () {
    ...
    };
    KingJoffery.prototype.marry = function () {
    ...
    };
    return KingJoffery;
})();

implements 一个 HandOfTheKing class

let LordTywin = (function () {
    function LordTywin() {
    }
    LordTywin.prototype.makeDecision = function () {
    };
    return LordTywin;
})();

具体的工厂类

let LannisterFactory = (function () {
    function LannisterFactory() {
    }
    LannisterFactory.prototype.getKing = function () {
        return new KingJoffery();
    }
    LannisterFactory.prototype.getHandOfTheKing = function () {
        return new LordTywin();
    };
    return LannisterFactory;
})();

上面代码简单地实例化每个所需类的新实例, 并返回它们。
下面是不同的世袭家族的一般形式

let TargaryenFactory = (function () {
    function TargaryFactory() {
    }
    TargaryFactory.prototype.getKing = function () {
        return new KingAerys();
    }
    TargaryFactory.prototype.getHandOfTheKing = function () {
        return new LordConnington();
    }
    return TargaryFactory;
})();

To make use of the Abstract Factory we’ll first need a class that requires the use of
some ruling family

let CourtSession =(function () {
    function CourtSession(abstractFactory) {
        this.abstractFactory = abstractFactory;
        this.COMPLAINT_THRESHOLD = 10;
    }
    CourtSession.prototype.complaintPresented = function (complaint) {
        if (complaint.severity < this.COMPLAINT_THRESHOLD){
            this.abstractFactory.getHandOfTheKing().makeDecision();
        }else
            this.abstractFactory.getKing().makeDecision();
    };
    return CourtSession;
})();

We can now call this CourtSession class and inject different functionality
depending on which factory we pass in:

let courtSession1 = new CourtSession(new TargaryenFactory());
courtSession1.complaintPresented({ severity : 8});
courtSession1.complaintPresented({ severity: 12});

let courtSession2 = new CourtSession(new LannisterFactory());
courtSession2.complaintPresented({ severity: 8});
courtSession2.complaintPresented({ severity: 12});

It may also be a useful pattern when attempting to ensure that a set of objects be
used together without substitutions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值