《读书笔记》设计模式——装饰模式

装饰模式:动态地给一个对象添加一些额外的职责。

                   就增加功能来说,装饰模式相比生成子类更为灵活。


public interface Person {
	void eat();
}
public class Man implements Person{

	@Override
	public void eat() {
		// TODO 自动生成的方法存根
		System.out.println("男人在吃饭。。。");
	}

}
public abstract class Decorator implements Person{
	protected Person person;
	public void setPerson(Person person){
		this.person = person;
	}
	public void eat(){
		person.eat();
	}
}
public class ManDecoratorA extends Decorator {
	public void eat(){
		super.eat();
		reEat();
		System.out.println("ManDecoratorA");
	}
	private void reEat() {
		// TODO 自动生成的方法存根
		System.out.println("再吃一顿。。。");
	}
}
public class ManDecoratorB extends Decorator {
	public void eat(){
		super.eat();
		System.out.println("========");
		System.out.println("ManDecoratorB");
	}
}
public class Test {
	public static void main(String[] args) {
		Man man = new Man();
		ManDecoratorA man1 = new ManDecoratorA();
		ManDecoratorB man2 = new ManDecoratorB();
		//装饰过程
		man1.setPerson(man);
		man2.setPerson(man1);
		man2.eat();
	}
}

》》例程:

     1,Person—— 定义一个对象接口,可以给对象动态添加功能。

     2,Man——Person的实现类,就是给此类型的对象添加功能。

     3,Decorator——维持一个指向Person对象的指针,并定义一个与Person接口一致的接口。

     4,ManDecoratorA、ManDecoratorB——负责向Man对象添加功能。


》》适用场景:

    1,在不影响其他对象的情况下,动态地给单个对象添加功能。

    2,当不能采用子类的方法进行扩充时。


》》小结:

   装饰模式是为已有功能动态地添加更多功能的一种方式。

   它把每个要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。

   因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择的、按顺序地使用装饰功能包装对象了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值