[关闭]
@BertLee 2017-08-10T16:35:09.000000Z 字数 1682 阅读 856

青出于蓝而胜于蓝的装饰者模式

序言

  装饰者模式能够在不使用创造子类的情况下,将对象的功能加以扩展,如果要撤销功能的话,也比较方便。
在装饰者模式中,含有的角色:

  • 抽象构件角色:接口或者抽象类,给出了需要装饰的接口。
  • 具体构件角色:类,包含了被装饰者所有的功能。
  • 装饰角色:类,持有抽象构建角色的委托实例,并实现了抽象构件角色的接口。
  • 具体装饰角色:类,继承装饰角色,对于需要装饰的方法进行增强。

装饰者模式

  装饰者的结构如下图:

套路:
1. 创建1个抽象装饰类
2. 创建委托实例,由客户端初始化
3. 实现抽象构件接口,通过委托实例,与原来接口保持一致
4. 创建具体装饰类,继承抽象装饰类,对要增强的功能增强

  1. /**
  2. * 抽象构件角色,士兵战斗接口
  3. */
  4. public interface Fightable {
  5. //穿盔甲
  6. public void wearArmour();
  7. //佩剑
  8. public void carrySword();
  9. }
  1. /**
  2. * 具体构件角色,士兵
  3. */
  4. public class Soldier implements Fightable{
  5. public void wearArmour() {
  6. System.out.println("身穿连衣裙");
  7. }
  8. public void carrySword() {
  9. System.out.println("佩戴铅笔刀");
  10. }
  11. }
  1. /**
  2. * 抽象装饰角色,士兵装饰者
  3. */
  4. public class SoldierDecorator implements Fightable{
  5. private Fightable fightablePerson;
  6. public SoldierDecorator(Fightable fightablePerson){
  7. this.fightablePerson = fightablePerson;
  8. }
  9. //原封不动
  10. public void wearArmour() {
  11. fightablePerson.wearArmour();
  12. }
  13. //原封不动
  14. public void carrySword() {
  15. fightablePerson.carrySword();
  16. }
  17. }
  1. /**
  2. * 具体装饰者,士兵包裹类
  3. */
  4. public class SoldierWrapper extends SoldierDecorator {
  5. public SoldierWrapper(Fightable fightablePerson) {
  6. super(fightablePerson);
  7. }
  8. @Override
  9. public void wearArmour() {
  10. super.wearArmour();
  11. System.out.println("增强后---------");
  12. System.out.println("穿戴铠甲");
  13. }
  14. @Override
  15. public void carrySword() {
  16. super.carrySword();
  17. System.out.println("增强后-----------");
  18. System.out.println("佩戴七星宝刀");
  19. }
  20. }
  1. /**
  2. * 测试装饰者模式
  3. */
  4. public class DecoratorTest {
  5. @Test
  6. public void testDecorator(){
  7. SoldierWrapper soldierWrapper = new SoldierWrapper(new Soldier());
  8. soldierWrapper.carrySword();
  9. System.out.println("分割线------------");
  10. soldierWrapper.wearArmour();
  11. }
  12. }

简化装饰者模式

  1. 去掉抽象构件接口,抽象装饰类直接继承继承具体构件角色,即SoldierDecorator继承Solider
  2. 去掉抽象装饰类,具体装饰类直接实现抽象构件接口

后记

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注