开发者

Which pattern to use

I have a class - call it ThankYou that delivers these. Based on the different implementations, generic or Facebook, I need to deliver customized layout. Right now, I am building the HTML in JS and delivering the layout.

1) Sign up for email newsletters (for generic and Facebook implementa开发者_JAVA技巧tion) 2) Teaser content (for generic implementation) 3) Facebook like(for Facebook ThankYou implementation)

Which design pattern do you think this is better implemented using - Factory or Mediator? I am just starting to utilize some design patterns in my code and would like to start off on the right foot.

Some notes: a) Although the functionality might be the same, the layout might be different for generic and Facebook

If I don't use a design pattern, I could easily do this using an 'if' statement, but I am just looking for a more elegant solution.


I think that Factory more suitable in this case. You have base class (interface) called IThankYou that implements common methods and two classes extending base functionality. Factory stores mapping between type and class.

Small example code:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜