设计模式之装饰模式

定义:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

结构图:


示例代码:

public abstract class Component {

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

	@Override
	public void operation() {
		// TODO Auto-generated method stub
		System.out.println("具体对象操作!");
	}

}
public class ConcreteDecoratorB extends Decorator {
	
	@Override
	public void operation() {
		// TODO Auto-generated method stub
		super.operation();
		System.out.println("具体装饰对象B的操作");
	}

	private void AddedBehavior() {
		System.out.println("我是B操作");
	}
}

public class ConcreteDecoratorA extends Decorator {

	private String addedState;
	
	@Override
	public void operation() {
		// TODO Auto-generated method stub
		super.operation();
		addedState = "New State";
		System.out.println("具体装饰对象A的操作");
	}

}
客户端代码如下所示:

public class Client {

	public static void main(String[] args) {
		
		ConcreteComponent c = new ConcreteComponent();
		ConcreteDecoratorA d1 = new ConcreteDecoratorA();
		ConcreteDecoratorB d2 = new ConcreteDecoratorB();
		d1.setComponent(c);
		d2.setComponent(d1);
		d2.operation();
//		d1.setComponent(d2);
//		d1.operation();
	}

}
运行结果如下:

具体对象操作!
具体装饰对象A的操作
具体装饰对象B的操作


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值