装饰者模式

装饰者模式

  • 作用:动态的给一个对象添加额外功能


栗子:


拿武器来说:

  • 武器Weapon(被装饰对象的基类)
  • 武器有剑啦,斧头等(具体被装饰的对象)
  • 装饰者抽象类Decorator
  • 武器可以吸血,还有可以复活(具体装饰者)

*主要是在具体装饰者中要有Weapon(被装饰对象的基类)这个属性

看代码:

被装饰的基类Weapon

/*
 * 被装饰的基类
 * */
interface Weapon{
	
	void show();
}

具体被装饰的对象(斧头)
/*
 * 被装饰的具体对象(斧头)
 * */
class Axe implements Weapon{
	//武器的名字
	String name;

	//构造函数
	public Axe(String name) {
		this.name = name;
	}
	
	//实现接口的方法
	public void show() {
		System.out.println("我是"+name);
	}
}

具体被装饰对象(剑)
/*
 * 被装饰的具体对象(剑)
 * */
class Sword implements Weapon{
	//武器的名字
	String name;

	//构造函数
	public Sword(String name) {
		this.name = name;
	}
	
	//实现接口的方法
	public void show() {
		System.out.println("我是"+name);
	}
}

装饰器
/*
 * 装饰器
 * */
abstract class Decorator implements Weapon{
	//这里就不做什么了
}

具体装饰类(吸血)
/*
 * 吸血
 * */
class SuckBoold extends Decorator{
	String type;
	//主要是要有这个属性
	Weapon weapon;

	//构造函数
	public SuckBoold(String type,Weapon weapon) {
		this.type = type;
		this.weapon = weapon;
	}
	
	public void show() {
		System.out.println("我在"+type);
		weapon.show();
	}
}

具体装饰类(复活)
/*
 * 复活功能
 * */
class Resurgence extends Decorator{
	String type;
	//主要是要有这个属性
	Weapon weapon;

	//构造函数
	public Resurgence(String type,Weapon weapon) {
		this.type = type;
		this.weapon = weapon;
	}
	
	
	public void show() {
		System.out.println("我在"+type);
		weapon.show();
	}
}

测试类:

1,我要一把会吸血的剑

	public static void main(String[] args) {
		//吸血的剑
		new SuckBoold("吸血", new Sword("绝世好贱")).show();
	}

输出:

我在吸血
我是绝世好贱

2.复活的剑

	public static void main(String[] args) {
		//吸血的剑
		new Resurgence("复活", new Sword("绝世好贱")).show();
	}

输出:

我在复活
我是绝世好贱

3,我要一把会吸血又会复活的斧头

	public static void main(String[] args) {
		//吸血的剑
		new Resurgence("复活", new SuckBoold("吸血", new Axe("多功能斧头"))).show();
	}

输出:

我在复活
我在吸血
我是多功能斧头




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值