java设计模式——装饰模式

本文详细介绍了设计模式中的组件与装饰器模式,通过代码实例展示了如何使用装饰器模式来扩展对象的功能。代码示例中包括了一个具体的对象、两个装饰器类及其操作过程,最终输出了特定的顺序信息。

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

《大话设计模式》第六章

package ch06.b;

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


 

package ch06.b;

public class ConcreteComponent extends Component {

	@Override
	public void operation() {
		System.out.println("具体对象的操作");
	}

}


 

package ch06.b;

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

	@Override
	public void operation() {
		if (component != null) {
			component.operation();
		}
	}

}


 

package ch06.b;

public class ConcreteComponentA extends Decorator {

	public ConcreteComponentA(Component component) {
		super(component);
	}

	@Override
	public void operation() {
		System.out.println("before ConcreteComponentA.operation");
		super.operation();
		System.out.println("after ConcreteComponentA.operation");
	}

}


 

package ch06.b;

public class ConcreteComponentB extends Decorator {

	public ConcreteComponentB(Component component) {
		super(component);
	}

	@Override
	public void operation() {
		System.out.println("before ConcreteComponentB.operation");
		super.operation();
		System.out.println("after ConcreteComponentB.operation");
	}

}


 

package ch06.b;

import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Component comp = new ConcreteComponentA(new ConcreteComponentB(new ConcreteComponent()));
		comp.operation();
		
		//下面是JDK中的装饰器模式的经典例子
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		
		try {
			fos = new FileOutputStream("1.txt");
			bos = new BufferedOutputStream(fos);
			bos.write(65);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeCloseable(bos);
			closeCloseable(fos);
		}
	}
	
	private static void closeCloseable(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
				closeable = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


运行一下代码,输出:

before ConcreteComponentA.operation
before ConcreteComponentB.operation
具体对象的操作
after ConcreteComponentB.operation
after ConcreteComponentA.operation


看看代码,看看JDK,应该就能理解了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值