设计模式——装饰器

73 阅读1分钟

装饰器的作用是动态地将功能附加到对象上,可以灵活的替代子类来扩展功能。

  1. 定义接口
public interface Weapon {
  void attack();
  int getAttackPower();
}
  1. 简单实现类
public class Sword implements Weapon {

    @Override
    public void attack() {
        System.out.println("攻击!");
    }

    @Override
    public int getAttackPower() {
        return 10;
    }
}
  1. 装饰类
public class EnchantSword implements Weapon {
    private Weapon weapon;
    
    public EnchantSword(Weapon weapon){
        this.weapon = weapon;
    }
    
    @Override
    public void attack() {
        weapon.attack();
        System.out.println("附魔攻击!");
    }

    @Override
    public int getAttackPower() {
        return weapon.getAttackPower()+10;
    }
}

使用:

Sword sword = new Sword();

EnchantSword en = new EnchantSword(sword);
en.attack();
en.getAttackPower();