装饰模式
动态地给一个对象添加一个额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
代码实现
Component抽象类——定义一个对象接口,可以给这些对象动态的添加一些职责。
public abstract class Component{
public abstract void operation();
}
ConcreteComponent类——定义一个具体的对象。
public class ConcreteComponent extends Component{
public void operation(){
System.out.println("具体对象的操作!");
}
}
Decorator类——装饰抽象类,继承了Component接口,从外部扩展Component类的功能。
public abstract class Decortor extends Component{
protected Component component;
public void setComponent(Component component){
this.component = component;
}
//重写operation()方法,实际执行component的operation()
public void operation(){
if(component != null){
component.operation();
}
}
}
ConcreteComponentA和ConcreteComponentB类——装饰类的具体实现
public class ConcreteComponentA{
private String addedState;//本类独有的属性,区别于ConcreteComponentB
public void operation(){
super.operation();//先运行父类的operation()方法,再去执行本类特有的功能,相当于对原Component进行了装饰
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}
public class ConcreteComponentB{
//本类独有的方法,区别于ConcreteComponentA类
public void addedBehavior(){
}
public void operation(){
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}
}