本文共 1720 字,大约阅读时间需要 5 分钟。
装饰模式又名包装(Wrapper)模式
装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案 装饰模式以对客户透明的方式动态的给一个对象附加上更多的责任
装饰模式的角色:
实现的场景:
1.Java中I/O流的实现具体实现:
componet:
public interface Component { public void doSomething();}
Concrete Component:
public class ConcreteComponent implements Component { @Override public void doSomething() { System.out.println("具体功能直接实现"); }}
decorator:
public class Decorator implements Component { private Component component; public Decorator(Component component){ this.component = component; } @Override public void doSomething() { component.doSomething(); }}
concrete decorator:
public class ConcreteDecorator1 extends Decorator { public ConcreteDecorator1(Component component) { super(component); } @Override public void doSomething() { super.doSomething(); this.doAnotherThing(); } private void doAnotherThing() { System.out.println("功能A"); }}
client:
public class Client { public static void main(String[] args) { Component component = new ConcreteDecorarot2(new ConcreteDecorator1(new ConcreteComponent())); component.doSomething(); }}
返回结果:
具体功能直接实现
功能A 功能B
可以进行debug追踪执行过程,先进入到ConcreteDecorarot2执行doSomething,然后执行父类Decorator中的doSomething,该方法会执行传入的component中的doSomething也就是传入的ConcreteDecorarot1,ConcreteDecorarot1的执行最后也会执行到传入进来的component的doSomething,也就是最里面的ConcreteComponent的doSomething,然后从里往外返回出去。
转载地址:http://tmrgi.baihongyu.com/