JAVA 设计模式之装饰模式

一、​​​​​​定义:

不改变原有对象的基础上,将额外附加功能添加到对象上,提供了比继承更有弹性的替代方案(扩展原有对象功能)。

二、角色

抽象构件角色(Component):通常定义一个抽象类或者接口,定义一些方法,方法的实现由子类实现或者自己实现。

具体构件角色(Concrete Component):是Component的子类,实现了对应的方法。通常被称为“被装饰者”。

装饰角色(Decorator):是Component的子类,它是具体装饰角色共同实现的抽象类、类或者接口,并持有一个Component类型的对象引用。它的主要作用是把客户端的调用委派到被装饰类。

具体装饰角色(Concrete Decorator):是Decorator的子类,是具体的装饰类,也是Component的子类。主要功能就是定义具体的装饰功能。

三、装饰器类图

JAVA 设计模式之装饰模式

四、应用

装饰器模式主要应用在 java/io流中、maybatis的cache中等。

五、代码实例(mybais--cache)

  //抽象构件类(Component):定义cache接口,并定义了一些方法。

public interface Cache {
    String getId();
    void putObject(Object var1, Object var2);
    Object getObject(Object var1);
    Object removeObject(Object var1);
    void clear();
    int getSize();
    ReadWriteLock getReadWriteLock();
}

//具体构件角色(Concrete Component):被装饰器

public class PerpetualCache implements Cache {
    private final String id;
    private Map<Object, Object> cache = new HashMap();
    public PerpetualCache(String id) {
        this.id = id;
    }
    public String getId() {
        return this.id;
    }
    public int getSize() {
        return this.cache.size();
    }
    public void putObject(Object key, Object value) {
        this.cache.put(key, value);
    }
    public Object getObject(Object key) {
        return this.cache.get(key);
    }
    public Object removeObject(Object key) {
        return this.cache.remove(key);
    }
    public void clear() {
        this.cache.clear();
    }
    public ReadWriteLock getReadWriteLock() {
        return null;
    }
    public boolean equals(Object o) {
        if (this.getId() == null) {
            throw new CacheException("Cache instances require an ID.");
        } else if (this == o) {
            return true;
        } else if (!(o instanceof Cache)) {
            return false;
        } else {
            Cache otherCache = (Cache)o;
            return this.getId().equals(otherCache.getId());
        }
    }
    public int hashCode() {
        if (this.getId() == null) {
            throw new CacheException("Cache instances require an ID.");
        } else {
            return this.getId().hashCode();
        }
    }
}

//mybatis中省略了具体装饰角色(Concrete Decorator),直接使用装饰角色

JAVA 设计模式之装饰模式

例如BlockingCache、FifoCache、LoggingCache等装饰角色,直接实现Cache接口,定义额外的附加功能。