以前讲了接口,封装,继承,单例等,如今就须要应用这些特性来完成一些设计模式了。首先吧以前的代码打包成一个新的JSjavascript
// 设计模式公用代码 exports.Interface = function (object, methods) { for (var i = 0, len = methods.length; i < len; i++) { if (typeof methods[i] !== 'string') { throw new Error('Interface constructor expects method names to be passed in as a string.'); } object[methods[i]] = function () { throw new Error(this.constructor.name + ' Interface function is undefined'); }; } }; exports.Extend = function (subClass, superClass) { var F = function () { }; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; subClass.superclass = superClass.prototype; if (superClass.prototype.constructor == Object.prototype.constructor) { superClass.prototype.constructor = superClass; } } exports.Clone = function (object) { function F() { } F.prototype = object; return new F; } exports.Augment = function (receivingClass, givingClass) { if (arguments[2]) { // Only give certain methods. for (var i = 2, len = arguments.length; i < len; i++) { receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]]; } } else { // Give all methods. for (methodName in givingClass.prototype) { if (!receivingClass.prototype[methodName]) { receivingClass.prototype[methodName] = givingClass.prototype[methodName]; } } } }
1.工厂接口是工厂方法模式的核心,与调用者直接交互用来提供产品。java
2.工厂实现决定如何实例化产品,是实现扩展的途径,须要有多少种产品,就须要有多少个具体的工厂实现。设计模式
1.在任何须要生成复杂对象的地方,均可以使用工厂方法模式。有一点须要注意的地方就是复杂对象适合使用工厂模式,而简单对象,无需使用工厂模式。测试
2.工厂模式是一种典型的解耦模式,迪米特法则在工厂模式中表现的尤其明显。假如调用者本身组装产品须要增长依赖关系时,能够考虑使用工厂模式。将会大大下降对象之间的耦合度。ui
3.当须要系统有比较好的扩展性时,能够考虑工厂模式,不一样的产品用不一样的实现工厂来组装。this
var DP = require("./DesignPattern.js"); function CarFactory() {//定义工厂 this.run = function () { console.log(this.productCar()+'启动'); } DP.Interface(this, ['productCar']); } function PorscheFactory() {//实例化保时捷工厂 this.__proto__ = new CarFactory(); this.productCar = function () { return '保时捷'; } } function TractorFactory() {//实例化拖拉机工厂并不重写接口测试接口定义 this.__proto__ = new CarFactory(); } var Porsche = new PorscheFactory(); Porsche.run(); var Tractor = new TractorFactory(); Tractor.run();
因为javascript没有原生接口,因此须要本身想方法来实现接口这个原则。使用了接口之后就能够方便实现工厂模式。prototype