装饰模式的UML类图
你会发现,在装饰模式中,除了对抽象接口的实现,更重要的还有对抽象接口的聚合。
装饰模式一般适应于常为系统已有的功能动态的添加更多的功能。
1、将会更新的功能的进行抽象
package decorate_1;
public interface Component {
public void opration();
}
2、原有功能实现
package decorate_1;
public class ConcreteComponent implements Component {
@Override
public void opration() {
System.out.println("原有功能");
}
}
3、将要附加装饰进行抽象
package decorate_1;
//为子类提供模板
public abstract class Decorator implements Component{
Component base = null;
@Override
public void opration() {
if(base != null){
base.opration();
}
}
public void setComponent(Component base){
this.base = base;
}
}
4、具体装饰类A
package decorate_1;
public class ConcreteDecoratorA extends Decorator {
private String addedState;
@Override
public void opration() {
super.opration(); //先运行原有的operation()
//...下面为本类自带的特殊逻辑和其他具体操作
this.addedState = "abc";
System.out.println("ConcreteDecoratorA operations");
}
public void printState(){ //该自带的特殊方法
System.out.println(this.addedState);
}
}
5、具体装饰类B
package decorate_1;
public class ConcreteDecoratorB extends Decorator {
@Override
public void opration() {
super.opration();
this.otherOperation();
}
public void otherOperation(){
System.out.println("ConcreteDecoratorB operations");
}
}
6、Main客户端
package decorate_1;
public class Main {
public static void main(String[] args) {
ConcreteComponent concreateComponent = new ConcreteComponent();
ConcreteDecoratorA cda = new ConcreteDecoratorA();
ConcreteDecoratorB cdb = new ConcreteDecoratorB();
//装饰
cda.setComponent(concreateComponent);
cdb.setComponent(cda);
//开始执行
cdb.opration();
}
}
使用装饰模式的一个例子
装饰模式就像穿衣服,如穿衣服需要先穿内裤,再穿上衣或者裤子,或者再加个外套, 比如哪天你不想穿外套,或者在外套外再加层风衣,穿衣的方式是多样的。
如:
将Person作为ConcreteComponent,其中show()显示姓名。
Component接口中抽象出show()方法。
将穿衣服、裤子、鞋子抽象成Decorator,并具体实现ConcreteDecorator。