首页 > 代码库 > 设计模式--装饰模式

设计模式--装饰模式

复习设计模式--装饰模式
装饰模式 在不修改已经存在的类的情况下,动态的添加新的功能,实现即插即用,开放关闭原则

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();
	}

}