装饰模式

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

应用场景:

动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。不改变接口的前提下,增强所考虑的类的性能。

何时使用:

    1)需要扩展一个类的功能,或给一个类增加附加责任。

    2)需要动态的给一个对象增加功能,这些功能可以再动态地撤销。

    3)需要增加一些基本功能的排列组合而产生的非常大量的功能,从而使继承变得    不现实。


例子来自大话设计模式

可倒推理解代码

 //装饰模式
class Person
{
	public Person(){}
	private String name;
	public Person(String name){
		this.name = name;
	}
	public void show(){
		System.out.println("装扮的"+name);
	}
}
//服饰类
class Finery extends Person
{
	protected Person component;
	public void Decorate(Person component){
		this.component = component;
	}
	public void show(){
		if(component != null){
			component.show();
		}
	}
	
}

class TShirts extends Finery
{
	public void show(){

		System.out.println("大T恤");
		super.show();
	}
}
class BigTrouser extends Finery
{
	public void show(){

		System.out.println("垮裤");
		super.show();
	}
}
class Sneakers extends Finery
{
	public void show(){

		System.out.println("球鞋");
		super.show();
	}
}
public class Main {

	public static void main(String[] args) {
		Person xc = new Person("小菜");
		System.out.println("第一种装扮:");
		Sneakers s = new Sneakers();
		BigTrouser bt = new BigTrouser();
		TShirts ts = new TShirts();
		
		s.Decorate(xc);
		bt.Decorate(s);
		ts.Decorate(bt);
		ts.show();

		System.out.println("第二种装扮:");
		bt.Decorate(xc);
		s.Decorate(bt);
		ts.Decorate(s);
		ts.show();
	}

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值