装饰器模式

装饰器模式应用于下面的场景:

不确定客户端对某个类的对象需要什么功能,所以一般只给客户端一个默认的实现,具有基本的功能。比如对于InputStream这个抽象类会有一个FileInputStream的实现,这个实现提供文件输入流的基本功能。但是有时候客户端会加个缓冲功能,或者想把一个InputStream或者其子类转换成DataInputStream为了实现跨平台,我们可以把已经传在的对象传进构造器即可,这就是装饰器模式。

下面有一个简单的装饰器模式例子,

package net.liuyx.test;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;

public class DecoratorTest {
	public static void main(String[] args) {
		Woman woman;
		woman = new ChineseWoman();
		woman.cook();

		System.out.println("===============================");
		System.out.println("Descorate the woman with knowledge");
		System.out.println("The new woman then have knowledge decorated!");
		System.out.println("===============================");

		Knowledge knowWoman = new Knowledge(woman);
		knowWoman.cook();

		System.out.println("===============================");
		System.out.println("Descorate the woman with beauty");
		System.out.println("The new woman then have beauty decorated!");
		System.out.println("===============================");

		Beautify beautifulWoman = new Beautify(woman);
		beautifulWoman.cook();

		System.out.println("===============================");
		System.out.println("Descorate the woman with beauty and knowledge");
		System.out
				.println("The new woman then have beauty and knowledge decorated!");
		System.out.println("===============================");

		Knowledge perfectWoman = new Knowledge(new Beautify(woman));
		perfectWoman.cook();
	}
}

interface Woman {
	void cook();
}

class ChineseWoman implements Woman {

	@Override
	public void cook() {
		System.out.println("这个女人能做饭");
	}

}
/**
 *装饰器类含有被装饰类接口的一个引用,而且装饰器类与被装饰器类必须有同一个接口,
 *这样就能把一个子类对象传到装饰器构造器内,从而达到装饰的作用
 * @author liuyx
 *
 */
class Descorator implements Woman {
	private Woman woman;

	public Descorator(Woman woman) {
		this.woman = woman;
	}

	@Override
	public void cook() {
		woman.cook();
	}

}

class Knowledge extends Descorator {
	public Knowledge(Woman woman) {
		super(woman);
	}

	private void haveKnowledge() {
		System.out.println("这个女人做法挺有章法");
	}

	@Override
	public void cook() {
		super.cook();
		haveKnowledge();//用知识武装女人
	}

}

class Beautify extends Descorator {
	public Beautify(Woman woman) {
		super(woman);
	}

	private void haveBeautify() {
		System.out.println("这个女人饭菜做得很漂亮");
	}

	@Override
	public void cook() {
		super.cook();
		haveBeautify();//用漂亮的厨艺武装女人
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值