为了账号安全,请及时绑定邮箱和手机立即绑定

码仔漫画|重学设计模式之装饰者模式

码仔带你学习设计模式

https://img3.sycdn.imooc.com/5fd0d6060001210607250492.jpg

https://img4.sycdn.imooc.com/5fd0d6070001f14907250492.jpg

https://img2.sycdn.imooc.com/5fd0d6070001111007250492.jpg

https://img1.sycdn.imooc.com/5fd0d6080001565d07250492.jpg

https://img1.sycdn.imooc.com//5fd0d69d00014e2007250492.jpg

https://img1.sycdn.imooc.com/5fd0d60900010f0707250492.jpg

https://img1.sycdn.imooc.com//5fd0d6be0001524b07250492.jpg

https://img1.sycdn.imooc.com/5fd0d60d0001d2ad07250492.jpg

https://img3.sycdn.imooc.com/5fd0d60e0001093507250492.jpg

https://img1.sycdn.imooc.com//5fd0d6de0001450607250492.jpg

https://img4.sycdn.imooc.com/5fd0d61a0001b12307250492.jpg

https://img3.sycdn.imooc.com/5fd0d61b0001989107250492.jpg

https://img1.sycdn.imooc.com//5fd0d7020001235207250492.jpg

https://img4.sycdn.imooc.com/5fd0d61c0001521806400432.jpg

https://img1.sycdn.imooc.com//5fd0d71f0001235207250492.jpg

https://img2.sycdn.imooc.com/5fd0d61d0001c6ce07250492.jpg

代码

抽象基类

public abstract class 英雄 {  public abstract int 攻击()  public abstract int 冷却()
   ........
}

实现基类

public class 李白 extends 英雄 {   @Override
   public int 冷却(){      return 5;
  }
   ........
}

Buff 抽象类

public abstract Buff extends 英雄 {   public abstract int 攻击()  public abstract int 冷却()
   ........
}

不同 Buff 的实现类

public 红buff extends Buff {   private 英雄 英雄;   public 红buff(英雄 英雄){        this.英雄 = 英雄;
    }     @Override
   public int 攻击() {     return 英雄.攻击() + 红buff额外攻击;
   }
   .........
 
}public 蓝buff extends Buff {   private 英雄 英雄;   public 蓝buff(英雄 英雄){        this.英雄 = 英雄;
    }    @Override
   public int 冷却() {
     return 英雄.冷却()  + 蓝buff额外减少的冷却值;
   }
   .........

}

客户端

public class Client {
    public static void main(String[] args) {        // 没有buff的英雄
        英雄 无buff李白 = new 李白();       
        // 打了红
        红buff 红buff李白 = new 红buff(无buff李白);        // 再来个篮
        篮buff 红蓝buff李白 = new 篮buff(红buff李白);

    }
}

注意:以上代码块用中文编写类名、变量名是为了让大家更好的理解,在实战过程中记得替换成相对应的英文。

总结

https://img1.sycdn.imooc.com//5fd0d736000182eb06400485.jpg

出自《Head first 设计模式》

PS:

内容是我之前写过的,改成了漫画的形式。

大家觉得不错就点个赞,如有建议可以欢迎留言讨论。


点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
全栈工程师
手记
粉丝
67
获赞与收藏
1543

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消