2010年4月30日 星期五

Design Pattern 設計模式 Decorator 裝飾者模式

Today, we use "Decorator"
今天來玩玩Decorator

javascript:
cd=console.debug;
function Component(base)
{
 this.base=null;
 try{
  this.base=base;
 }catch(e){}
 
 this.name="";
 this.value=0;
 
 this.getDes=function(){
  var s='';
  try{
   s+=this.base.getDes();
  }catch(e){}
  s+=this.name+','
  return s;
 }
 
 this.cost=function(){
  var v=0;
  try{
   v+=this.base.cost();
  }catch(e){}
  v+=this.value;
  return v;
 } 
}

/*inherit*/
function Espresso(base)
{
 var d=new Component(base);
 d.name="Espresso";
 d.value=100;
 return d;
};

function Mocha(base)
{
 var d=new Component(base);
 d.name="Mocha";
 d.value=10;
 return d;
};

function Soy(base)
{
 var d=new Component(base);
 d.name="Soy";
 d.value=50;
 return d;
};

(function(){
 var e= new Espresso(),
 m= new Mocha(e),
 a= new Mocha(m),
 s= new Soy(a);
 
 cd(s.cost());
 cd(s.getDes());
})();

python:
class Component():
    base=None
    name=''
    value=0
    
    def __init__(self,base=None):
        try:
            self.base=base
        except:
            pass

    def getDes(self):
        s=''
        try:
            s+=self.base.getDes()+','
        except:
            pass
        s+=self.name
        return s
    def cost(self):
        v=0;
        try:
            v+=self.base.value
        except:
            pass
        return v+self.value

class Espresso(Component):
    name='Espresso'
    value=2000
    pass
class Soy(Component):
    name='Soy'
    value=20
    pass

class Mocha(Component):
    name='Mocha'
    value=200
    pass

def main():
    s=Espresso()
    
    s=Mocha(s)
    s=Mocha(s)
    s=Soy(s)
    
    st=s.getDes()
    v=s.cost()
    print st
    print v

    
if __name__!='__main__':
    main()

沒有留言:

張貼留言