【设计模式】java装饰器模式

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。
这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

意图

  • 动态地给一个对象添加一些额外的职责。
  • 就增加功能来说,装饰器模式相比生成子类更为灵活。

主要解决

  • 一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

案例

在不修改原有的方法的条件下,给该方法功能。

1、原有接口类,实现类
//接口类
public interface Human {
    void height();
}


//实现类
public class ShortMan implements Human{
    @Override
    public void height() {
        System.out.println("我很矮");
    }
}



public class TallMan implements Human{
    @Override
    public void height() {
        System.out.println("我很高");
    }
}

2、抽象修饰类
package decorator;
//实现human接口
public abstract class HumanDecorator implements Human{
    //定义一个Human属性
    protected Human humanDecorator;

    //构造方法
    public HumanDecorator(Human humanDecorator) {
        this.humanDecorator = humanDecorator;
    }

    //重写
    @Override
    public void height() {
        humanDecorator.height();
    }
}

3、具体的修饰类
package decorator;

//继承修饰抽象类
public class GoodHumanDecorator extends HumanDecorator{
    //构造方法,里面调用的是父类的构造方法
    public GoodHumanDecorator(Human humanDecorator) {
        super(humanDecorator);
    }

    @Override
    public void height() {
        humanDecorator.height();
        //在原有基础代码上进行装饰,这就是装饰模式的用处了
        System.out.println("但是我很厉害");
    }


}

4、测试
package decorator;

public class Test {
    public static void main(String[] args) {
        new TallMan().height();
        new ShortMan().height();

        System.out.println("===================");
        new GoodHumanDecorator(new ShortMan()).height();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WalkerShen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值