[2014-11-17]Java笔记_装饰模式(Decorator)

本文详细介绍了装饰模式的概念及其在软件设计中的应用。装饰模式允许在不改变原有对象结构的前提下,动态地给对象添加新的职责,是一种替代继承的有效方式。文中通过具体的Java代码示例展示了装饰模式的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

· 装饰模式又名包装(Wrapper)模式

· 装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

· 装饰模式以对客户透明的方式动态的给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。

· 装饰模式可以在不创建更多子类的情况下将对象的功能加以扩展。

· 装饰模式的角色:

         — 抽象构建角色(Component):给出一个抽象接口,以规范准备接受附加责任的对象。

         — 具体构建角色(Concrete Component):定义一个将要接收附加责任的类。

         — 装饰角色(Decorator):持有一个构建(Component)对象的引用,并定义一个与抽象构件接口一致的接口。

         — 具体装饰角色(Concrete Decorator):负责构件对象“贴上”附加的责任。

· 装饰模式的特点:

          — 装饰对象和真实对象有相同的接口。这样客户端对象就可以和真实对象相同的方式和装饰对象交互。

          — 装饰对象包含一个真实对象的引用(reference)

          — 装饰对象接收所有来自客户端的请求。它把这些请求转发给真实的对象。

          — 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部添加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。


package com.bob.decorator;

//抽象构件角色
public interface Component {
	public void doSomething();
}
package com.bob.decorator;

//具体构件角色
public class ConcreteComponent implements Component {
	@Override
	public void doSomething() {
		System.out.println("功能A");
	}
}
package com.bob.decorator;

//装饰角色
public class Decorator implements Component {	//与抽象构件接口一致的接口
	
	private Component component;	//持有一个构建对象的引用
	
	public Decorator(Component component){
		this.component = component;
	}
	
	@Override
	public void doSomething() {
		component.doSomething();
	}

}
package com.bob.decorator;

//具体装饰角色
public class ConcreteDecorator1 extends Decorator {

	//因为父类没有默认构造方法所以必须提供构造
	public ConcreteDecorator1(Component component){
		super(component);
	}
	
	@Override
	public void doSomething() {
		super.doSomething();
		this.doAnotherThing();	//子类执行完父类功能后自己附加的功能
	}
	
	//子类自己可以附加自己的功能
	private void doAnotherThing(){
		System.out.println("功能B");
	}
}
package com.bob.decorator;

//具体装饰角色
public class ConcreteDecorator2 extends Decorator {
	public ConcreteDecorator2(Component component){
		super(component);
	}
	
	@Override
	public void doSomething() {
		super.doSomething();
		this.doAnotherThing();	//子类执行完父类功能后自己附加的功能
	}
	
	//子类自己可以附加自己的功能
	private void doAnotherThing(){
		System.out.println("功能C");
	}
}
package com.bob.decorator;

public class Client {
	public static void main(String[] args) {
	
		/*
		//节点流
		Component component = new ConcreteComponent();
		//过滤流
		Component component2 = new ConcreteDecorator1(component);
		//过滤流
		Component component3 = new ConcreteDecorator2(component2);
		
		component3.doSomething();
		*/
		Component component = new ConcreteDecorator1(new ConcreteDecorator2(new ConcreteComponent()));
		component.doSomething();
		
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值