装饰模式Decorator

来源:互联网 发布:.store域名值钱吗 编辑:程序博客网 时间:2024/06/04 17:56
    这种 模式用于一个类的原有功能不能满足客户需求了,需要对原来的
功能有所加强,这时就可以用到装饰模式。
   这种功能的加强主要是能通过在原有功能的基础上,增加功能。

举个例子

  小孩子有个功能--》吃饭

  现在为它加个功能,除了会吃饭,还要自己会做饭

  后来又要加一个功能,除了会做会吃,还要会洗碗


  这里有个基础功能,为了不破环原有类的,我们可以继承这个类,重写一些方法达到效果。

   也可以用装饰类

  也可以提取出基本功能---》吃饭,封装在一个接口中

  public interface baseMethod{

   public void eat();
  
}

   public class child  implements baseMethod
{

    public void eat(){}

}
    
    现在有两个功能需要装饰,为了降低耦合,每个装饰分出一个类

   每个类又都要调用eat()这个基本方法,为了不重复调用这个方法,
  构建一个父类,每个子类根据需求在相应的逻辑位置调用超类的方法super()
就实现了对基本方法的调用

     public class baseDecorator implements baseMethod
{
      baseMethod b;         
      
      baseDecorrator(baseMethod basemethod ){

    b=basemethod;
}

          public void eat(){
           
b.eat();

};
          
}
    public class chaoCaiDecorator extends baseDecorator {

    
       public chaoCaiDecorator(baseMethod decotator){
8           super(decorator);
}


    public void cookMeal(){}


    public void eat(){

      cookMeal();

      super.eat();
}
}
   
        public class washDishDecorator extends baseDectorator{
    

       public  washDishDecorator(baseMethod method){
super(method);
}

   public void eat(){
    
super.eat(); 

  washDish();
}

public void washDish(){}
       



}
  
    
   
  




  


    
 
0 0
原创粉丝点击