Java设计模式之装饰者模式

DECORATOR (Object Structural) 
Purpose 
    Allows for the dynamic wrapping of objects in order to modify 
their existing responsibilities and behaviors. 
Use When 
    1 Object responsibilities and behaviors should be dynamically 
       modifiable. 
    2 Concrete implementations should be decoupled from 
      responsibilities and behaviors. 
    3 Subclassing to achieve modification is impractical or impossible. 
    4 Specific functionality should not reside high in the object hierarchy. 
    5 A lot of little objects surrounding a concrete implementation is 
      acceptable. 
Example 
    Many businesses set up their mail systems to take advantage of 
decorators. When messages are sent from someone in the company 
to an external address the mail server decorates the original 
message with copyright and confidentiality information. As long 
as the message remains internal the information is not attached. 
This decoration allows the message itself to remain unchanged 
until a runtime decision is made to wrap the message with 
additional information. 

Java代码 
  1. package javaPattern;  
  2.   
  3. interface Component{  
  4.     public void operation();  
  5. }  
  6. class ConcreteComponent implements Component{  
  7.     public void operation(){  
  8.         System.out.println("某具体操作方法");  
  9.     }  
  10. }  
  11. public abstract class Decorator implements Component{  
  12.   
  13.     public abstract void operation();   
  14.     public abstract void addedBehavior();  
  15. }  
  16. class ConcreteDecorator extends Decorator{  
  17.   
  18.     private String addedState;  
  19.     @Override  
  20.     public void operation() {  
  21.         System.out.println("具体装饰类的某具体方法");  
  22.           
  23.     }  
  24.     @Override  
  25.     public void addedBehavior(){  
  26.         System.out.println("新增加的方法");  
  27.     }  
  28. }  

你可能感兴趣的:(java,设计模式,UP)