java设计模式之装饰模式

来源:互联网 发布:最新杭州网络诈骗案 编辑:程序博客网 时间:2024/06/05 17:00

java设计模式参考文章:
Java设计模式实战,23种设计模式介绍以及在Java中的实现,Java设计模式, Java经典设计模式之五大创建型模式


## 定义 ##

装饰者模式(Decorator): 又称包装器(Wrapper), 可以动态地为一个对象添加一些额外的职责.就增加功能来说, 装饰者模式是一种用于替代继承的技术, 他无须通过增加子类继承就能扩展对象的已有功能, 而是使用对象的关联关系代替继承关系 , 更加灵活, 同时还可避免类型体系的快速膨胀.

## 代码示例 ##

/** * @author bwx * @date 2017/11/27 * 被装饰的抽象接口 */public interface Component {    void operator();}/** * @author bwx * @date 2017/11/27 * 具体的被装饰者 */public class ConcreteComponent implements Component {    public void operator() {        System.out.println("具体对象" + this.toString() + "的操作");    }}/** * @author bwx * @date 2017/11/27 * 抽象装饰器 */public abstract class Decorator implements Component {    protected Component component;    public Decorator(Component component) {        this.component = component;    }}/** * @author bwx * @date 2017/11/27 * 具体的装饰器 */public class BeforeAdviceDecorator extends Decorator {    public BeforeAdviceDecorator(Component component) {        super(component);    }    public void operator() {        System.out.println(" -> 前置增强");        this.component.operator();    }}/** * @author bwx * @date 2017/11/27 * 具体的装饰器 */public class AfterAdviceDecorator extends Decorator {    public AfterAdviceDecorator(Component component) {        super(component);    }    public void operator() {        this.component.operator();        System.out.println("后置增强 -> ");    }}/** * @author bwx * @date 2017/11/27 * 装饰模式 */public class Main {    public static void main(String[] args) {        // 裸Component        Component component = new ConcreteComponent();        component.operator();        // 前置增强        Component component1 = new BeforeAdviceDecorator(component);        component1.operator();        // + 后置增强        component = new AfterAdviceDecorator(component);        component.operator();    }}

##优点##

1.有效地将类的核心职责和装饰功能区分开;被装饰者和装饰者是松耦合关系。满足开-闭原则。2.去除相关类中重复的装饰逻辑;3.可以对一个对象装饰多次, 构造出不同行为的组合, 得到功能更强大的对象;4.具体构件类和具体装饰类可独立变化, 且用户可根据需要增加新的具体构件子类和具体装饰子类.
原创粉丝点击