装饰模式(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();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值