回顾设计模式--装饰图案 装饰图案 如果没有改变的情况下现有的类,动态添加新功能。即插即用,开闭原则
public interface Man { public void killMonster();}public class BatMan implements Man { public String name; public BatMan(String name) { this.name = name; } @Override public void killMonster() { System.out.println("蝙蝠侠" + name + "開始打怪兽!"); }}public class XMan implements Man { @Override public void killMonster() { System.out.println("X-Man 開始打怪兽!"); }}//Decorator 加入武器 进行油漆装饰public abstract class Weapon implements Man { protected Man man; public void setMan(Man man) { this.man = man; } public Man getMan() { return man; } @Override public void killMonster() { man.killMonster(); } }public class Sword extends Weapon { private String swordName; public Sword(String swordName) { this.swordName = swordName; } @Override public void killMonster() { System.out.println("获取一把剑。剑名:" + swordName); super.killMonster(); }}public class Gun extends Weapon { public String gunName; private int bulletCount = 10; public Gun(String gunName) { this.gunName = gunName; } @Override public void killMonster() { System.out.println("发放武器 " + gunName + ",装有子弹" + bulletCount + "发!
"); super.killMonster(); } } public class GiveBullet extends Weapon { private int bulletCount; public GiveBullet(int bulletCount) { this.bulletCount = bulletCount; } @Override public void killMonster() { System.out.println("额外发放子弹" + bulletCount + "发!
"); super.killMonster(); } } public class DecoratorTest { public static void main(String[] args) { Man man = new BatMan("Wayne"); //Man man = new XMan(); //man.killMonster(); Weapon weapon = new Gun("AK"); //weapon.setMan(man); //weapon.killMonster(); Weapon bullet = new GiveBullet(100); Weapon sword = new Sword("莫邪"); //加入子弹 bullet.setMan(man); //加入gun weapon.setMan(bullet); //加入剑 sword.setMan(weapon); sword.killMonster(); } }
版权声明:本文博主原创文章。博客,未经同意不得转载。