一)介绍
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
何时使用:在不想增加很多子类的情况下扩展类。
如何解决:将具体功能职责划分,同时继承装饰者模式。
优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
使用场景:
1、扩展一个类的功能。
2、动态增加功能,动态撤销。
二)UML类图
三)实现
第一步:创建一个操作类
package com.oysept.decorator;
public abstract class Component {
public abstract void operation();
}
第二步:创建一个操作实现类
package com.oysept.decorator;
public class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.println("具体对象的操作!");
}
}
第三步:创建一个装饰类
package com.oysept.decorator;
public abstract class Decorator extends Component {
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
public void operation () {
if (component != null) {
component.operation();
}
}
}
第四步:创建具体的装饰实现类
装饰A:
package com.oysept.decorator;
public class ConcreteDecoratorA extends Decorator {
private String addedState;
public void operation () {
super.operation();
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}
装饰B:
package com.oysept.decorator;
public class ConcreteDecoratorB extends Decorator {
public void operation () {
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}
private void addedBehavior() {
System.out.println("BBBBBBB");
}
}
第五步:测试
package com.oysept.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); // 装饰A
d2.setComponent(d1); // 装饰B
d2.operation();
}
}
运行结果:
识别二维码关注个人微信公众号
本章完结,待续,欢迎转载!
本文说明:该文章属于原创,如需转载,请标明文章转载来源!