例子:
package com.zoey.designPattern.Decorator;
/*
* 装饰模式(Decorator):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活
* Component是定义一个对象接口,可以给这些对象动态地添加职责。
*/
public abstract class Component {
public abstract void Operation();
}
package com.zoey.designPattern.Decorator;
//ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责
public class ConcreteComponent extends Component {
@Override
public void Operation() {
System.out.println("具体对象的操作");
}
}
package com.zoey.designPattern.Decorator;
//Decorator装饰抽象类,继承了component,从外类来扩展component类的功能,但对于Component来说,
//是无需知道Decorator的存在的
public class Decorator extends Component {
protected Component component;
@Override
public void Operation() {
if(component != null){
component.Operation();
}
}
public void setComponent(Component component) {
this.component = component;
}
}
package com.zoey.designPattern.Decorator;
//ConcreteDecoratorA具体装饰对象,起到给Component添加职责的功能
public class ConcreteDecoratorA extends Decorator {
@SuppressWarnings("unused")
private String addedState;
public void Operation(){
super.Operation();
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}
package com.zoey.designPattern.Decorator;
//ConcreteDecoratorB具体装饰对象,起到给Component添加职责的功能
public class ConcreteDecoratorB extends Decorator {
public void Operation(){
super.Operation();
addedbehavior();
System.out.println("具体装饰对象B的操作");
}
private void addedbehavior(){
System.out.println("一条测试的方法!");
}
}
package com.zoey.designPattern.Decorator;
public class Test {
/*
* 装饰模式,优点:有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑
*/
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();
}
}
结果:
具体对象的操作
具体装饰对象A的操作
一条测试的方法!
具体装饰对象B的操作