设计模式--结构型--装饰模式

一、装饰模式简介(Brief Introduction)

动态地给一个对象添加一些额外的职责。

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

二、解决的问题(What To Solve)

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

三、装饰模式分析(Analysis)

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

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

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

ConcreteDecorator:实际的装饰器对象,实现具体要向被装饰器对象添加的功能

四、实例代码

1、Component接口及其实现

public interface Component {
	public void operation();
}
public class ConcreteComponent implements Component {

	public void operation() {
		System.out.println("=========ConcreteComponent=========");
	}
}
2、Decorator及其实现

public abstract class Decorator implements Component{

	private Component component;
	public Decorator(Component component){
		this.component = component;
	}
	public void operation() {
		this.component.operation();
	}
}
public class ConcreteDecoratorA extends Decorator {

	public ConcreteDecoratorA(Component component){
		super(component);
	}
	
	public void operation(){
		System.out.println("======operation调用前 添加信息A=====");
		super.operation();
		System.out.println("======operation调用结束 添加信息A=====");
	}
}
public class ConcreteDecoratorB extends Decorator {

	public ConcreteDecoratorB(Component component){
		super(component);
	}
	
	public void operation(){
		System.out.println("======operation调用前 添加信息B=====");
		super.operation();
		System.out.println("======operation调用结束 添加信息B=====");
	}
}

3、客户端调用

public class Client {

	public static void main(String[] args) {
		Component c1 = new ConcreteComponent();
		Decorator d1 = new ConcreteDecoratorA(c1);
		Decorator d2 = new ConcreteDecoratorB(c1);
		d1.operation();
		System.out.println();
		d2.operation();
	}
}

运行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值