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

2020/12/10 8:25:24

本文主要是介绍码仔漫画|重学设计模式之装饰者模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

码仔带你学习设计模式

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

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

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

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

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

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

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

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

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

http://img2.sycdn.imooc.com/5fd0d6de0001450607250492.jpg

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

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

http://img3.sycdn.imooc.com/5fd0d7020001235207250492.jpg

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

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

http://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李白);

    }
}

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

总结

http://img2.sycdn.imooc.com/5fd0d736000182eb06400485.jpg

出自《Head first 设计模式》

PS:

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

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




这篇关于码仔漫画|重学设计模式之装饰者模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程