美文网首页
设计模式-装饰模式

设计模式-装饰模式

作者: liuzhimi | 来源:发表于2019-04-22 22:34 被阅读0次

    介绍

    装饰模式可以动态地给一个对象添加一些额外地指责。

    使用场景
    需要透明且动态地扩展类的功能时。

    优点
    装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

    缺点
    多层装饰嵌套比较复杂。

    UML类图

    Decorator.jpg

    代码实现

    Role.java

    public abstract class Role {
    
        public abstract int attack();
        
        public abstract int regeneration();
    }
    

    Hero.java

    public class Hero extends Role {
    
        @Override
        public int attack() {
            return 100;
        }
    
        @Override
        public int regeneration() {
            return 10;
        }
    }
    

    Buff.java

    public abstract class Buff extends Role {
    
    }
    

    RedBuff.java

    public class RedBuff extends Buff {
    
        private Role role;
        
        public RedBuff(Role role) {
            this.role = role;
        }
    
        @Override
        public int attack() {
            return role.attack() + 50;
        }
    
        @Override
        public int regeneration() {
            return role.regeneration();
        }
    }
    

    BlueBuff.java

    public class BlueBuff extends Buff {
    
        private Role role;
        
        public BlueBuff(Role role) {
            this.role = role;
        }
    
        @Override
        public int attack() {
            return role.attack();
        }
    
        @Override
        public int regeneration() {
            return role.regeneration() + 10;
        }
    }
    

    Main.java

    public class Main {
    
        public static void main(String[] args) {
            Role hero = new Hero();
            System.out.println("Hero: Attack-" + hero.attack() + " Regeneration-" + hero.regeneration());
            Role redBuff = new RedBuff(hero);
            System.out.println("Hero With RedBuff: Attack-" + redBuff.attack() + " Regeneration-" + redBuff.regeneration());
            Role blueBuff = new BlueBuff(redBuff);
            System.out.println("Hero With RedBuff And BlueBuff: Attack-" + blueBuff.attack() + " Regeneration-" + blueBuff.regeneration());
        }
    }
    

    输出:

    Hero: Attack-100 Regeneration-10
    Hero With RedBuff: Attack-150 Regeneration-10
    Hero With RedBuff And BlueBuff: Attack-150 Regeneration-20
    

    相关文章

      网友评论

          本文标题:设计模式-装饰模式

          本文链接:https://www.haomeiwen.com/subject/wkcpgqtx.html