zoukankan      html  css  js  c++  java
  • Java设计模式---装饰模式(Decorator)

    1.  装饰模式(Decorator Pattern)定义:

         动态地给一个对象添加额外的职责(功能)。相比生成子类,装饰模式更加灵活。

    2.  装饰模式中的角色说明:

         Component抽象角色: Component是一个接口或者抽象类,是我们最原始的对象

         ConcreteCompont具体角色: ConcreteCompont是继承或者实现了Component的类,也是我们需要装饰的类

         Decorator抽象装饰角色:抽象装饰者类,继承或者实现了Component,并且有一个私有的Component对象

         DecoratorOne具体装饰角色:继承了Decorator,一般在这个类为原始对象扩展功能

    3.  实现示例代码:

     Component接口: 

    public interface Component {
        
    	public void operator();
    	
    }
    ConcreteCompont类:

    public class ConcreteComponent implements Component {
    
    	@Override
    	public void operator() {
    		
    		System.out.println("我是需要被装饰的操作方法....");
    
    	}
    
    }
    抽象装饰者Decorator类:

    public abstract class Decorator implements Component{
        
    	private Component component;
    	
    	//通过构造函数传递被装饰者
    	public Decorator(Component component) {
    		super();
    		this.component = component;
    	}
    	
    	@Override
    	public void operator() {
    		this.component.operator();	
    	}
    	 
    }
    具体装饰者类:

    public class DecoratorOne extends Decorator {
        
    	//定义被装饰者
    	public DecoratorOne(Component component) {
    		super(component);
    	}
    	
    	//重写父类的操作方法 
        @Override
        public void operator() {
        	this.decorator_one();
        	super.operator();
        }
        
        //定义装饰方法
        private void  decorator_one(){
        	System.out.println("来自一号装饰者的装饰处理");
        }
    
    }
    public class DecoratorTwo extends Decorator {
        
    	//定义被装饰者
    	public DecoratorTwo(Component component) {
    		super(component);
    	}
    	
    	//重写父类的操作方法 
        @Override
        public void operator() {
        	super.operator();
        	this.decorator_two();
        }
        
        //定义装饰方法
        private void  decorator_two(){
        	System.out.println("来自二号装饰者的装饰处理");
        }
    
    }
    装饰测试类:

    public class Test {
       
    	public static void main(String[] args) {
    		
    		 Component component=new ConcreteComponent();
    		 //第一次装饰
    		 component=new DecoratorOne(component);
    		 //第二次装饰
    		 component=new DecoratorTwo(component);
    		 //装饰之后调用
    		 component.operator();
    		
    	}
    }
    输出结果:

    来自一号装饰者的装饰
    我是需要被装饰的操作方法....
    来自二号装饰者的装饰
    
    4.  装饰模式的使用场景

       1.需要扩展一个类的功能或者给一个类增加附加功能

       2.需要动态的为一个对象增加功能,这些功能可以动态的撤销







  • 相关阅读:
    ZOJ 1002 Fire Net (火力网)
    UVa OJ 117 The Postal Worker Rings Once (让邮差只走一圈)
    UVa OJ 118 Mutant Flatworld Explorers (变体扁平世界探索器)
    UVa OJ 103 Stacking Boxes (嵌套盒子)
    UVa OJ 110 MetaLoopless Sorts (无循环元排序)
    第一次遇到使用NSNull的场景
    NSURL使用浅析
    从CNTV下载《小小智慧树》
    NSDictionary and NSMutableDictionary
    Category in static library
  • 原文地址:https://www.cnblogs.com/elgin-seth/p/5293768.html
Copyright © 2011-2022 走看看