现在的位置: 首页 > 综合 > 正文

装饰器模式

2013年11月06日 ⁄ 综合 ⁄ 共 1344字 ⁄ 字号 评论关闭

1.装饰器模式的定义

动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式比生成子类更为灵活

2.装饰器模式的UML图

Component:组件对象的接口,可以给这些对象动态的添加职责

ConcreteComponent:具体的组件对象,实现组件对象接口,通常就是被装饰器装饰的原始对象,也就是可以给这个对象添加职责

Decorator:所有装饰器的抽象父类,需要定义一个与组件接口一致的接口,并持有一个Component对象,其实就是持有一个被装饰的对象

3.代码实现

public abstract class Component
{
	public void operation();
}

public class ConcreteComponent extends Component{
   public void operation(){
   
   }
}


public abstract class Decorator extends Component
{
	protected Component component;
	public Decorator(Component component){
	      this.component=component;
	}

	public void operation(){
	   this.component.operation();
	
	}
}


public class ConcreteDecoratorA extends Decorator
{
   private String addedState;
   public String getAddedState(){
      return this.addedState;
   }

   public void setAddedState(String addedState){
       this.addedState=addedState;
   }

    public ConcreteDecoratorA(Component component){
	        this.component=component;
	}

	public void operation(){
	    this.component=compnent;
	}
}



public class ConcreteDecoratorB extends Decorator
{
   private String addedState;
   public String getAddedState(){
      return this.addedState;
   }

   public void setAddedState(String addedState){
       this.addedState=addedState;
   }

    public ConcreteDecoratorB(Component component){
	        this.component=component;
	}

	public void operation(){
	    this.component=compnent;
	}
}


public class  Client
{
	public static void main(String[] args){
	    Component component=new ConreteComponent();
		Decorator decorator=new ConcreteDecoratorA(component);
		decorator.operation();
	}
}

4.装饰模式的本质:动态组合

抱歉!评论已关闭.