设计模式-装饰模式

2019-04-22  本文已影响0人  liuzhimi

介绍

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

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

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

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

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
上一篇下一篇

猜你喜欢

热点阅读