设计模式之装饰者模式

一、定义

装饰(Decorator)模式的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

二、优缺点

优点:

  • 采用装饰模式扩展对象的功能比采用继承方式更加灵活。
  • 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。

缺点:

  • 装饰模式增加了许多子类,如果过度使用会使程序变得很复杂。

三、代码实现举例

(1)创建一个接口

public interface Component {
    public void operation();
}

(2)创建实现接口的实体类

public class F_Component implements Component {
    @Override
    public void operation() {
        System.out.println("This is F_Component!!!");
    }
}

public class S_Component implements Component {
    @Override
    public void operation() {
        System.out.println("This is S_Component!!!");
    }
}

(3)创建实现了 Component 接口的抽象装饰类

public abstract class ComponentDecorator implements Component {
    protected Component component;

    public ComponentDecorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
       component.operation();
    }
}

(4)创建扩展了 ComponentDecorator 类的实体装饰类

public class OneComponentDecorator extends ComponentDecorator {
    public OneComponentDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        component.operation();
        setOne(component);
    }

    private void setOne(Component component){
        System.out.println("This is OneComponentDecorator!!! ");
    }
}

(5)使用 OneComponentDecorator 来装饰 Component对象。

public class DecortorTest {

    public static void main(String[] args) {
        F_Component f_component = new F_Component();
        ComponentDecorator f_cd = new OneComponentDecorator(new F_Component());
        ComponentDecorator s_cd = new OneComponentDecorator(new S_Component());
        System.out.println("--- F_Component -----");
        f_component.operation();
        System.out.println("--- f_cd -----");
        f_cd.operation();
        System.out.println("--- s_cd -----");
        s_cd.operation();
    }

}

输出:

--- F_Component -----
This is F_Component!!!
--- f_cd -----
This is F_Component!!!
This is OneComponentDecorator!!! 
--- s_cd -----
This is S_Component!!!
This is OneComponentDecorator!!! 

四、总结

装饰模式主要包含以下角色。

  1. 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
  2. 具体构件(Concrete    Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
  3. 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  4. 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值