代码之家  ›  专栏  ›  技术社区  ›  pablorc

javascript中的模板方法

  •  5
  • pablorc  · 技术社区  · 15 年前

    我希望在JavaScript中实现模板方法模式。

    我有一个具有一些子类的PropertyDecorator:OpenButtonDecorator、SeeButtonDecorator等等。我想在属性修饰器中有下一个函数:

    var build = function(){
       decorate(); //Abstract in PropertyDecorator, defined in subclasses
       return le.build();
    }
    

    我如何才能让这个场景工作?也许我实现了错误的继承:s(也有帮助:)

    提前谢谢。

    1 回复  |  直到 15 年前
        1
  •  12
  •   Miguel    10 年前

    function PropertyDecorator()
    {
       this.build = function()
       {
          var decoration=this.decorate();
          return "The decoration I did: "+decoration;
       };
    }
    
    //we set the parent (those prototype that instances of this class will delegate calls to) 
    OpenButtonDecorator.prototype = new PropertyDecorator();
    function OpenButtonDecorator()
    {
       this.decorate = function()
       {
         return "open button";
       };
    }
    
    
    SeeButtonDecorator.prototype = new PropertyDecorator();
    function SeeButtonDecorator()
    {
       this.decorate = function()
       {
          return "see button";
       };
    }
    
    
    
    var decorators=Array(new SeeButtonDecorator(),new OpenButtonDecorator());
    for (var decorator in decorators){
        document.writeln(decorators[decorator].build());
    }
    

    build()

    function PropertyDecorator()
    {
       this.build = function()
       {
          var decoration=this.decorate();
          return "The decoration I did: "+decoration;
       };
    }
    

    build decorate()

    function SeeButtonDecorator()
    {
       this.decorate = function()
       {
          return "see button";
       };
    }
    

    The decoration I did: see button
    
    推荐文章