装饰模式

来源:互联网 发布:mariadb与mysql 编辑:程序博客网 时间:2024/06/10 09:15

decorator 模式的功能是:给一个对象添加一些额外的职责(操作),虽然此功能可以用继承实现,但装饰模式比生成子类更灵活些。

装饰的意思:就是包装一下。把另的对象包装一下。我这里只简单示例下怎么使用。


业务接口 Component:

 package com.chenlb.dp.decorator; 
  
 /**
  * 业务接口
  */ 
 public interface Component { 
  
     void operation(); 
 }


具体业务 ConcreteComponent:

  package com.chenlb.dp.decorator; 
  
 /**
  * 具体业务类.
  */ 
 public class ConcreteComponent implements Component { 
  
     public void operation() { 
         System.out.println("I'm "+this.getClass().getName()); 
     } 
  
 }


装饰 Decorator:

 package com.chenlb.dp.decorator; 
 
/**
 * 装饰类.
 */ 
public class Decorator implements Component { 
 
    private Component component; 
 
    public Decorator(Component component) { 
        this.component = component; 
    } 
 
    public void operation() { 
        component.operation(); 
    } 
 
}



执行前装饰 BeforeDecorator:

 package com.chenlb.dp.decorator; 
  
 /**
  * 在业务执行前加点额外的操作.
  */ 
 public class BeforeDecorator extends Decorator { 
  
     public BeforeDecorator(Component component) { 
         super(component); 
     } 
  
     public void operation() { 
         before(); 
         super.operation(); 
     } 
  
     private void before() { 
         System.out.println("before: I'm "+this.getClass().getName()); 
     } 
  
 }


执行后装饰 AfterDecorator:

  package com.chenlb.dp.decorator; 
  
 /**
  * 在业务执行完后添加额外的操作.
  */ 
 public class AfterDecorator extends Decorator { 
  
     public AfterDecorator(Component component) { 
         super(component); 
     } 
  
     public void operation() { 
         super.operation(); 
         after(); 
     } 
  
     private void after() { 
         System.out.println("after: I'm "+this.getClass().getName()); 
     } 
 }


运行示例 Demo:

 package com.chenlb.dp.decorator; 
 
public class Demo { 
 
    public static void main(String[] args) { 
        Component component = new ConcreteComponent(); 
        component.operation(); 
        System.out.println("----------------------------------------"); 
        component = new BeforeDecorator(new ConcreteComponent()); 
        component.operation(); 
        System.out.println("----------------------------------------"); 
        component = new AfterDecorator(new ConcreteComponent()); 
        component.operation(); 
        System.out.println("----------------------------------------"); 
        component = new AfterDecorator(new BeforeDecorator(new ConcreteComponent())); 
        component.operation(); 
        System.out.println("----------------------------------------"); 
        component = new BeforeDecorator(new AfterDecorator(new ConcreteComponent())); 
        component.operation(); 
    } 
 
}