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

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Media(中介者)模式</title> <script type="text/javascript" src="js/jquery.js"></script> </head> <body> <h2>Media(中介者)模式</h2> <p>行为设计模式。公开一个统一的接口,系统的不同部分可以通过该接口进行通信。</p> <p>确保组件的交互是通过这个中心点来处理,而不是通过显示地引用彼此。</p> <p>这种模式可以帮助我们解耦系统并提高组件的可重用性</p> <hr> <script> // 1 基本实现 var mediator = (function (){ // 存储可被广播或监听的topic var topics = {}; // 订阅一个topic,提供一个回调函数,一旦topic被广播就执行该回调 var subscribe = function (topic, fn){ if(!topics[topic]){ topics[topic] = []; } topics[topic].push({context: this, callback: fn}); return this; }; // 发布/广播事件到程序的剩余部分 var publish = function (topic){ var args; if(!topics[topic]){ return false; } // call 和 apply 方法都是用来调用“不属于自身的方法”,apply第二参数必须是数组 // 下面的代码相当于 arguments.slice,但是arguments本身没有 slice方法 // slice 方法是用来截取数组 // arguments 是实参“数组” args = Array.prototype.slice.call(arguments, 1); for(var i = 0, l = topics[topic].length; i < l; i++){ var subscription = topics[topic][i]; subscription.callback.apply(subscription.context, args); // subscription.callback(arguments[1]); } return this; }; return { publish: publish, subscribe: subscribe, installTo: function (obj){ obj.subscribe = subscribe; obj.publish = publish; } } })(); </script> <h3>简单实现</h3> <form id="chatForm"> <label for="fromBox">Your Name:</label> <input id="fromBox" type="text"> <br> <label for="toBox">Send to:</label> <input id="toBox" type="text"> <br> <label for="chatBox">Message:</label> <input id="chatBox" type="text"> <button action="submit">Chat</button> </form> <div id="chatResult"></div> <script type="text/javascript"> $("#chatForm").on("submit", function (e){ e.preventDefault(); // 从UI上获取chat的数据 var text = $("#chatBox").val(), from = $("#fromBox").val(), to = $("#toBox").val(); // 将数据发布到newMessage主题上 mediator.publish("newMessage", {message: text, from: from, to: to}); }); // 将新信息附加到聊天记录结果上 function displayChat(data){ var date = new Date(), msg = data.from + " said \""+data.message+"\" to "+ data.to; $("#chatResult").prepend(""+msg+" ("+date.toLocaleTimeString()+")"); } // 记录消息日志 function logChat(data){ if(window.console){ console.log(data); } } // 通过mediator订阅提交的newMessage主题 mediator.subscribe("newMessage", displayChat); mediator.subscribe("newMessage", logChat); </script> </body> </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值