09装饰模式

装饰模式

<设计模式其实很简单>笔记


①定义:

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


②代码:
//组件抽象父类
public abstract class Component{
	//抽象的基本操作
	public abstract void Operation();
}
//具体组件类
public class ConcreteComponent enxtends Component{
	//基本操作
	@Override
	public void Operation(){
		System.out.println("basic operation!");
	}
}
//装饰器类
public class Decorator extends Component{
	//仅供本类调用的Component对象
	protected Component component;
	//设置Component对象的方法,根据里氏代换原则,可以使用ConcreteComponent的对象做参数
	public void SetComponent(Component component){
		this.component = component;
	}
	//重写的基本操作方法
	@Override
	public void Operation(){
		if(component != null){
			component.Operation();
		}
	}
}
//装饰器A
public class ConcreteDecoratorA extends Decorator{
	private String addedState;
	//基本操作
	public void Operation(){
		super.Operation();
		addedState = "new state";
		System.out.println("this class has a" + 	addedState);
	}
}
//装饰器B
public class ConcreteDecoratorB extends Decorator{
	//基本操作
	public void Operation(){
		super.Operation();
		AddedBehavior();
	}
	private void AddedBehavior(){
		System.out.println("now the object has a new method");
	}
}
//客户端
public static void main(String[] args){
	ConcreteComponent concreteComponent = new ConcreteComponent();
	//实例化两个装饰器
	ConcreteDecoratorA cDecoratorA = new ConcreteDecoratorA();
	ConcreteDecoratorB cDecoratorB = new ConcreteDecoratorB();
	
	//对ConcreteComponent对象进行装饰
	cDecoratorA.SetComponent(concreteComponent);
	cDecoratorB.SetComponent(concreteComponent);
		
	//显示装饰后的结果
	cDecoratorA.Opration();
	cDecoratorB.Opration();
}


③适用的情况
当需要以不影响其他对象为前提实现动态、透明地给单个对象添加职责时。
当需要将对象的某些职责进行撤销操作时。
当不能用生成子类的方法进行当前系统的扩充时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值