设计模式之 装饰者模式
装饰者模式指在无须改变原有类及类的关系的情况下,动态扩展一个类的功能。它通过装饰者来包裹真实的对象,并动态地向对象添加或者撤销功能。
(1)定义Sourceable接口
public interface Sourceable{ public void createComputer(); }
(2)定义Sourceable接口的实现类
public class Source implements Sourceable{ private final static Log logger = LogFactory.getLog(Source.class); @Override public void createComputer(){ logger.info("create computer by Source"); } }
(3)定义装饰者类
public class Decorator implements Sourceable{ private final static Log logger = LogFactory.getLog(Decorator.class); private Sourceable source; public Decorator(Sourceable source){ super(); this.source = source; } @Override public void createComputer(){ source.createComputer(); logger.info("make system"); } }
Decorator扩展了原来的source的功能
(4)使用
public static void main(String[] args){ Sourceable source = new Source(); Sourceable obj = new Decorator(source); obj.createComputer(); }