Java设计模式-装饰者模式

背景

强化芯片可用来对机体进行强化,每个机体都可以装备1-4个强化芯片。强化芯片能够加强机体的属性和能力。现使用装饰者模式实现强化芯片的功能。

实现

机体抽象类:机体和芯片都要继承该抽象类

/**
 * 机体
 */
public abstract class Robot {

	/**
	 * 介绍
	 */
	public abstract void desc();
	
}

古铁机体:继承机体抽象类

public class AncientIron extends Robot {

	@Override
	public void desc() {
		System.out.println("古铁:南部响介的座驾,擅长近距离残弹攻击。");
	}

}

能量护罩芯片:同样继承机体抽象类

public class EnergyShield extends Chip {

	public EnergyShield(Robot robot) {
		super(robot);
	}

	@Override
	public void desc() {
		super.desc();
		System.out.println("强化芯片:能量护罩");
	}
}

推荐器芯片

/**
 * 推进器:机体移动力+2
 */
public class Propeller extends Chip {

	public Propeller(Robot robot) {
		super(robot);
	}

	@Override
	public void desc() {
		super.desc();
		System.out.println("强化芯片:推进器");
	}
	
}

修理配件芯片

/**
 * 修理配件:消耗品:使用后HP全回复
 */
public class RepairModule extends Chip {

	public RepairModule(Robot robot) {
		super(robot);
	}

	@Override
	public void desc() {
		super.desc();
		System.out.println("强化芯片:修理配件");
	}
}

**空芯片:模拟当前芯片为空

/**
 * 空芯片:表示该插槽还未被使用
 */
public class BlankChip extends Chip {

	public BlankChip(Robot robot) {
		super(robot);
	}
	
	@Override
	public void desc() {
		super.desc();
		System.out.println("强化芯片:------");
	}

}

测试类

public class DecoratorTest {
	
	public static void main(String[] args) {
		Robot robot = new RepairModule(new EnergyShield(new Propeller(new BlankChip(new AncientIron()))));
		robot.desc();
	}
	
}
测试结果
古铁:南部响介的座驾,擅长近距离残弹攻击。
强化芯片:------
强化芯片:推进器
强化芯片:能量护罩
强化芯片:修理配件
总结

装饰者模式是我们平时接触比较多的设计模式,如果你使用过IO流相关操作的话,你就明白IO流使用的就是装饰者模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值