`
chencvgk
  • 浏览: 15760 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

装饰模式(Decorator)

 
阅读更多

定义

动态将职责附加到对象上,若要扩展功能,装饰者提供了比继承更具弹性的代替方案。


能够解决什么问题

已经开发完毕的对象,后期由于业务需要,对旧的对象需要扩展特别多的功能,这时候使用给对象动态地添加新的状态或者行为(即装饰模式)方法,而不是使用子类静态继承。


优点

把类中的装饰功能从类中搬移出去,这样可以简化原有的类。有效地把类的核心功能和装饰功能区分开了


模式结构


Component: 定义了一个对象接口,可以给这些对象动态地添加职责

ConcreteComponent:定义了一个具体的对象,可以给这个具体的对象添加职责(需要被装饰的对象)

Decorator:抽象装饰类,继承了Component对象接口,从外类扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在

ConcreteDecoratorA:具体的装饰对象,起到给Component添加职责的功能

ConcreteDecoratorB:具体的装饰对象,起到给Component添加职责的功能


源代码

public interface Component {
	
	void operator();

}


public class ConcreteComponent implements Component {

	/**
	 * 装饰该方法,在此方法执行前后增加操作,前后操作可分离
	 */
	@Override
	public void operator() {
		System.out.println("被装饰的方法");
	}

}


/**
 * 装饰基类
 * 
 *
 */
public abstract class Decorator implements Component {
	//被装饰对象
	protected Component component;
	
	public Decorator(){
	}
	
	public Decorator(Component component){
		System.out.println("装饰基类带参数构造函数");
		this.component=component;
	}
	
	@Override
	public void operator() {
		//执行被装饰对象方法
		component.operator();
	}

	public Component getComponent() {
		return component;
	}

	public void setComponent(Component component) {
		this.component = component;
	}
	

}

public class ConcreteDecoratorA extends Decorator {

	public ConcreteDecoratorA(){
	
	}
	
	/**
	 * 构造器的继承,子类始终调用父类的缺省构造函数
	 * @param component
	 */
	public ConcreteDecoratorA(Component component){
		this.component=component;
	}
	
	@Override
	public void operator() {
		add_A();
		super.operator();
	}
	
	public void add_A(){
		System.out.println("=======装饰前========");
	}
	
}


public class ConcreteDecoratorB extends Decorator{

	public ConcreteDecoratorB(){
		
	}
	
	public ConcreteDecoratorB(Component component){
		this.component=component;
	}
	
	@Override
	public void operator() {
		super.operator();
		add_B();
	}
	
	public void add_B(){
		System.out.println("=======装饰后========");
	}
	
}


public class Client {
	
	public static void main(String[] args) {
		
		Decorator ca=new ConcreteDecoratorA();
		Decorator cb=new ConcreteDecoratorB();
		Component component=new ConcreteComponent();
		//new ConcreteDecoratorA(new ConcreteDecoratorB(new ConcreteComponent()));
		
		cb.setComponent(component);
		ca.setComponent(cb);
		
		ca.operator();
	}

}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics