装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
public interface Hero {
//学习技能
void learnSkills();
}
public class BlindMonk implements Hero {
private String name;
public BlindMonk(String name) {
this.name = name;
}
@Override
public void learnSkills() {
System.out.println(name + "学习了以上技能!");
}
}
//Decorator 技能栏
public class Skills implements Hero{
//持有一个英雄对象接口
private Hero hero;
public Skills(Hero hero) {
this.hero = hero;
}
@Override
public void learnSkills() {
if(hero != null)
hero.learnSkills();
}
}
//ConreteDecorator 技能:Q
public class Skill_Q extends Skills{
private String skillName;
public Skill_Q(Hero hero,String skillName) {
super(hero);
this.skillName = skillName;
}
@Override
public void learnSkills() {
System.out.println("学习了技能Q:" +skillName);
super.learnSkills();
}
}