结构型之装饰者模式

序言

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

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

1. 装饰者模式

  装饰者的结构如下图:

![](http://images2017.cnblogs.com/blog/946528/201708/946528-20170810162331417-1971852420.png)
> **套路**: > 1. 创建1个抽象装饰类 > 2. 创建委托实例,由客户端初始化 > 3. 实现抽象构件接口,通过委托实例,与原来接口保持一致 > 4. 创建具体装饰类,继承抽象装饰类,对要增强的功能增强
/**
 * 抽象构件角色,士兵战斗接口
 */
public interface Fightable {
    //穿盔甲
    public void wearArmour();
    //佩剑
    public void carrySword();
}
/**
 * 具体构件角色,士兵
 */
public class Soldier implements Fightable{
    public void wearArmour() {
        System.out.println("身穿连衣裙");
    }
    public void carrySword() {
        System.out.println("佩戴铅笔刀");
    }
}

/**
 * 抽象装饰角色,士兵装饰者
 */
public class SoldierDecorator implements Fightable{

    private Fightable fightablePerson;
    public SoldierDecorator(Fightable fightablePerson){
        this.fightablePerson = fightablePerson;
    }

    //原封不动
    public void wearArmour() {
        fightablePerson.wearArmour();
    }
    //原封不动
    public void carrySword() {
        fightablePerson.carrySword();
    }
}
/**
 * 具体装饰者,士兵包裹类
 */
public class SoldierWrapper extends SoldierDecorator {
    public SoldierWrapper(Fightable fightablePerson) {
        super(fightablePerson);
    }

    @Override
    public void wearArmour() {
        super.wearArmour();
        System.out.println("增强后---------");
        System.out.println("穿戴铠甲");
    }

    @Override
    public void carrySword() {
        super.carrySword();
        System.out.println("增强后-----------");
        System.out.println("佩戴七星宝刀");
    }
}
/**
 * 测试装饰者模式
 */
public class DecoratorTest {
    @Test
    public void testDecorator(){

        SoldierWrapper soldierWrapper = new SoldierWrapper(new Soldier());
        soldierWrapper.carrySword();
        System.out.println("分割线------------");
        soldierWrapper.wearArmour();
    }
}

2. 简化装饰者模式

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

后记

posted @   吃不了兜着走  阅读(139)  评论(0)    收藏  举报
编辑推荐:
· 微服务架构学习与思考:微服务拆分的原则
· 记一次 .NET某云HIS系统 CPU爆高分析
· 如果单表数据量大,只能考虑分库分表吗?
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
阅读排行:
· 精选 4 款免费且实用的数据库管理工具,程序员必备!
· Cursor:一个让程序员“失业”的AI代码搭子
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(6)
· 重生之我是操作系统(七)----内存管理(上)
· .NET 阻止Windows关机以及阻止失败的一些原因
点击右上角即可分享
微信分享提示