1.装饰器模式又名包装(Wrapper)模式。装饰器模式以对客户端透明的方式拓展对象的功能,是继承关系的一种替代方案。
2.结构图
3.再来看一个简单的例子
3.1定义一个component接口
public interface People {
void method();
}
3.2定义一个具体的实现接口类
public class XiaoMing implements People {
@Override
public void method() {
System.out.println("小明打扮自己");
}
}
3.3Decorator抽象类也实现接口,并且持有一个接口对象
public abstract class Decorator implements People {
private People component;
public Decorator(People component) {
this.component = component;
}
@Override
public void method() {
component.method();
}
}
3.4具体的装饰类,继承自decorator类,并且实现自己具体的装饰功能
public class DecoratorA extends Decorator {
public DecoratorA(People component) {
super(component);
}
@Override
public void method() {
super.method();
System.out.println("摸化妆品");
}
}
public class DecoratorB extends Decorator {
public DecoratorB(People component) {
super(component);
}
@Override
public void method() {
super.method();
System.out.println("戴首饰");
}
}
3.5测试类
public class Test {
public static void main(String[] args) {
//首先把实现类new出来
People component = new XiaoMing();
//把具体装饰者new出来
People component1 = new DecoratorA(component);
People component2 = new DecoratorB(component1);
component2.method();
}
}
打印结果:
4.总结:装饰模式主要是为了增加功能却不改变原有的功能而设计的,符合开闭原则;如上面的例子,在小明打扮自己时,可以首先调用打扮功能,接下来调用化妆品,再调用首饰;如果我们想再添加穿裙子功能,可以再写一个类,继承自抽象的decorator即可;原来的代码逻辑都不用动;调用时再多一步就好了;当功能多的时候;我们可以随意组合功能,得到我们想要的;