javascript的设计模式实现01之Factory

来源:互联网 发布:江西安全知识网络答题 编辑:程序博客网 时间:2024/06/05 17:28

Factory模式参考图片:


代码:

var Product = function() {};Product.prototype.operation = function() {};var ConcreteProduct = function() {this.operation = function() {console.log("concrete product operation");};};ConcreteProduct.prototype = new Product;ConcreteProduct.prototype.constructor = ConcreteProduct;var Creator = function() {};Creator.prototype.factoryMethod = function() {};Creator.prototype.getProduct = function() {return this.product;};Creator.prototype.setProduct = function(o) {this.product = o;};Creator.prototype.operation = function() {console.log("before operation");var product = this.factoryMethod();product.operation();console.log("end operation");return product;};var ConcreteFactory = function() {this.factoryMethod = function() {var o = new ConcreteProduct;this.setProduct(o);return o;};};ConcreteFactory.prototype = new Creator;ConcreteFactory.prototype.constructor = ConcreteFactory;var o = new ConcreteFactory;o.factoryMethod().operation();o.operation();

例子:

var Phone = function() {};Phone.prototype.makePhone = function() {console.log("make phone start...");};Phone.prototype.getInfo = function() {console.log("get info start...");};var IPhone = function(_sn) {this.sn = _sn;var Isuper = {makePhone: this.makePhone,getInfo: this.getInfo};this.getInfo = function() {Isuper.getInfo();console.log(this.label + " sn:" + this.sn);};{console.log("iphone start...");Isuper.makePhone();console.log("iphone end...");}};IPhone.prototype = new Phone;IPhone.prototype.constructor = IPhone;IPhone.prototype.label = "iphone";var HTC = function(_sn) {this.sn = _sn;var Isuper = {makePhone: this.makePhone,getInfo: this.getInfo};this.getInfo = function() {Isuper.getInfo();console.log(this.label + " sn:" + this.sn);};{console.log("htc start...");Isuper.makePhone();console.log("htc end...");}};HTC.prototype = new Phone;HTC.prototype.constructor = HTC;HTC.prototype.label = "htc";var Factory = function() {};Factory.prototype.getPhone = function() {console.log("factory start...");};var IPhoneFactory = function() {var ISuper = {getPhone: this.getPhone};this.getPhone = function() {ISuper.getPhone();console.log("iphone factory start...");return new IPhone(new Date().getMilliseconds());};};IPhoneFactory.prototype = new Factory;IPhoneFactory.prototype.constructor = IPhoneFactory;var HTCFactory = function() {var ISuper = {getPhone: this.getPhone};this.getPhone = function() {ISuper.getPhone();console.log("htc factory start...");return new HTC(new Date().getMilliseconds());};};HTCFactory.prototype = new Factory;HTCFactory.prototype.constructor = HTCFactory;var o = new HTCFactory;o.getPhone().getInfo();o.getPhone().getInfo();o.getPhone().getInfo();o = new IPhoneFactory;o.getPhone().getInfo();o.getPhone().getInfo();o.getPhone().getInfo();



0 0