码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式--装饰模式

时间:2014-05-09 13:56:56      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:设计模式   装饰模式   

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

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

}


设计模式--装饰模式,布布扣,bubuko.com

设计模式--装饰模式

标签:设计模式   装饰模式   

原文地址:http://blog.csdn.net/loveany121/article/details/25383841

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!