设计模式-结构型模式-装饰者模式
1.简介
有时候我们需要在现有的代码中,添加或者删除一些功能,同时对现有的功能又不影响,而且修改的这些功能又不足以做成一个(被装饰者)子类
聚合了将要装饰的接口,实现了原有对象一样的接口,代理委托原有对象的所有方法(变成了调用装饰类的方法)。在装饰类的子类方法中实现增强;
被装饰者的接口必须和装饰器的接口完全一致;
相当于是动态的扩展对象功能而不修改原有的对象,适配原接口,而不是使用子类化来扩展;
2.角色
具有一下角色
- Component :抽象组件 可以是一个接口
- ComponentImpl:被装饰者
- Decorator:这是一个抽象的组件装饰器
- ExtendedComponent:这是额外功能的组件装饰器
3.场景
还是举个JDK例子 ;Collections.synchronizedList 调用之后返回的list 返回的是一个线程安全的List
List<Object> list = new ArrayList<>();
list = Collections.synchronizedList(list);
//JDK源码
public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<>(list) :
new SynchronizedList<>(list)); // 返回的数据类型 ExtendedComponent
}
//ExtendedComponent SynchronizedList
static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> {
SynchronizedCollection ====>>> ///Decorator
//Decorator SynchronizedCollection 持有一个 Collection ,接口全部兼容 只是添加了 synchronized (mutex)
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
private static final long serialVersionUID = 3053995032091335093L;
final Collection<E> c; // Backing Collection
final Object mutex; // Object on which to synchronize
SynchronizedCollection(Collection<E> c) {
this.c = Objects.requireNonNull(c);
mutex = this;
}
SynchronizedCollection(Collection<E> c, Object mutex) {
this.c = Objects.requireNonNull(c);
this.mutex = Objects.requireNonNull(mutex);
}
public int size() {
synchronized (mutex) {return c.size();}
}
public boolean isEmpty() {
synchronized (mutex) {return c.isEmpty();}
}
public boolean contains(Object o) {
synchronized (mutex) {return c.contains(o);}
}
public Object[] toArray() {
synchronized (mutex) {return c.toArray();}
}
public <T> T[] toArray(T[] a) {
synchronized (mutex) {return c.toArray(a);}
}
public Iterator<E> iterator() {
return c.iterator(); // Must be manually synched by user!
}
public boolean add(E e) {
synchronized (mutex) {return c.add(e);}
}
public boolean remove(Object o) {
synchronized (mutex) {return c.remove(o);}
}
.................
}
架构图:
…
}