装饰模式
<设计模式其实很简单>笔记
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
//组件抽象父类
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();
}
③适用的情况
当需要以不影响其他对象为前提实现动态、透明地给单个对象添加职责时。
当需要将对象的某些职责进行撤销操作时。
当不能用生成子类的方法进行当前系统的扩充时。