23种设计模式之-装饰器模式

装饰器模式 Decorator Pattern


装饰器模式也叫包装模式(Wrapper Pattern),是指在不改变原有对象的基础之上,将功能附加到对象上,提供比继承更有弹性的替代方案(扩展原有对象的功能)。

装饰器模式就是一种特殊的代理模式;装饰器模式强调自身的功能扩展,用自己说了算的透明扩展,可动态定制扩展;代理模式强调代理过程的控制。
优点:

  • 1.装饰器是继承的有力补充,比继承灵活,不改变原有对象的情况下,动态地给一个对象扩展功能,即插即用。
  • 2.通过使用不同装饰类以及这些装饰类的排列组合,可实现不同效果。
  • 3.装饰器模式完成符合开闭原则。

缺点:

  • 1.会出现更多的代码,更多的类,增加程序的复杂性。
  • 2.动态装饰时,多层装饰会更加复杂。

在这里插入图片描述

public abstract class Component {

    public abstract void cost();
}
public abstract class Decorator extends Component {

    private Component component;

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

    @Override
    public void cost(){
        this.component.cost();
    }
}
public class ConcreteComponent extends Component {

    @Override
    public void cost() {
        System.out.println("ConcreteComponent basic cost.");
    }
}
public class ConcreteDecorator extends Decorator {

    public ConcreteDecorator(Component component) {
        super(component);
    }

    // 定义自己的修饰逻辑
    private void decorateMethod(){
        System.out.println("ConcreteDecorator add decorateMethod");
    }

    // 重写父类的方法
    public void cost(){
        this.decorateMethod();
        super.cost();
    }
}
public class DecoratorTest {

    public static void main(String[] args) {

        Component component = new ConcreteComponent();
        component = new ConcreteDecorator(component);
        component.cost();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值