2011-02-22 94 views
0

我有一个类 - 叫它ThankYou,它提供了这些。基于不同的实现,通用或Facebook,我需要提供自定义布局。现在,我在JS中构建HTML并提供布局。使用哪种模式

1)注册电子邮件通讯(仿制和Facebook实现) 2)预告内容(通用实现) 3)Facebook的喜欢(对于Facebook三江源实现)

哪些设计模式,你认为这使用工厂还是调解员更好地实施?我刚刚开始在代码中使用一些设计模式,并希望从右脚开始。

一些注意事项: 一)虽然其功能可能是相同的,布局可能是通用和Facebook不同

如果我不使用设计模式,我可以很容易地做到这一点使用一个“如果'声明,但我只是寻找更优雅的解决方案。

回答

0

我认为工厂更适合这种情况。您有称为IThankYou的基类(接口),它实现常用方法和两个扩展基本功能的类。工厂在类型和类之间存储映射。

小示例代码:

function IThankYou() {} 
IThankYou.prototype = { 
    templates: { // this is common field for all instances extending this class 
    like: '<div class="b-like">Like</div>', 
    },  

    like: function() { throw "Unimplemented" }, // this method is not implemented in base class 

    commonMethod: function() { } // this is common method 
}; 

function GenericThankYou (someParam) { this.someParam = someParam; }; 
GenericThankYou.prototype = new IThankYou; 
GenericThankYou.prototype.like = function() { 
    // there you could use base class fields and methods 
    this.commonMethod(); 
}; 

function FacebookThankYou (someParam) { this.someParam = someParam; }; 
FacebookThankYou.prototype = new IThankYou; 
FacebookThankYou.prototype.like = function() { 
    // there you could use base class templates map 
}; 

var ThankYouFactory = { 
    typeMap: { 
    'facebook' : FacebookThankYou, 
    'generic' : GenericThankYou 
    }, 
    getConstructor: function (type) { 
    return this.typeMap[type]; 
    } 
}; 

ThankYouFactory.getConstructor('facebook')(ctorParam); 
ThankYouFactory.getConstructor('generic')(ctorParam);