学习装饰模式

众所周知,面向对象设计有一个很重要的原则是对修改关闭,对扩展开放。在业务需求需要扩展时,我们常常使用继承的方式,让子类替代整个父类,但是这样会导致代码量急速增加。因此可以使用封装器,也就是装饰模式,简单来说,可以在不更改一个对象的情况下,动态的为这个对象添加一些行为。

买东西流程图

假设你平时出门逛街只买一杯奶茶就回家了,但是今天你想先买鸡蛋,然后再买橘子,最后买完奶茶再回家,流程如下图,我们并没有改变"买奶茶"这个行为,只不过在它之前添加了两个行为而已。

代码设计思路

  • 首先我们要定义一个接口ComponentInteface,这个接口中有个抽象方法用来定义行为,就叫buy方法吧
  • 其次,由于我们雷打不动,每次出门都会买奶茶,因此要定义一个买奶茶的类,实现ComponentInteface接口中的买东西方法,具体实现就是输出一句话:"我要买奶茶"
  • 现在需求来了,我们除了买奶茶,还要买鸡蛋和橘子,也就是对之前的行为进行装饰,因此我们需要定义一个装饰基类并实现ComponentInteface接口,这个类中保存着指向ComponentInteface实现类对象的引用
  • 最后,我们定义买鸡蛋和买橘子的类,并继承装饰基类,由于装饰基类是接口ComponentInteface的实现类,因此,继承了装饰基类的所有子类也都是ComponentInteface的隐式实现类。

代码实现

顶级接口

java 复制代码
public interface ComponentInteface {  
    void buy();  
}

买奶茶

java 复制代码
public class BuyMilkTea implements ComponentInteface{  
    @Override  
    public void buy() {  
        System.out.println("我要买奶茶");  
    }  
}

装饰器基类

java 复制代码
public class BaseDecorator implements ComponentInteface{  
    private ComponentInteface component;  

    public void setComponent(ComponentInteface component) {  
        this.component = component;  
    }  
    @Override  
    public void buy() {  
        component.buy();  
    }
}

买鸡蛋

java 复制代码
public class BuyEggDecorator extends BaseDecorator {  
    @Override  
    public void buy() {  
        System.out.println("我要买鸡蛋");  
        super.buy();  
    }  
}

买橘子

java 复制代码
public class BuyOrangeDecorator extends BaseDecorator {  
    @Override  
    public void buy() {  
    System.out.println("我要买橘子");  
        super.buy();  
    }  
}

测试

java 复制代码
public class main {  
    public static void main(String[] args) {  
        BaseDecorator baseDecorator = new BaseDecorator();  
        BuyEggDecorator buyEggDecorator = new BuyEggDecorator();  
        BuyOrangeDecorator buyOrangeDecorator = new BuyOrangeDecorator();  
        BuyMilkTea buyMilkTea = new BuyMilkTea();  

        baseDecorator.setComponent(buyEggDecorator);  
        buyEggDecorator.setComponent(buyOrangeDecorator);  
        buyOrangeDecorator.setComponent(buyMilkTea);  

        baseDecorator.buy();  
    }  
}

输出结果

相关推荐
一木 之林6 小时前
第 8 节 C++ 设计模式在 AI 推理 SDK 和 Agent 工具运行时中如何落地
c++·人工智能·设计模式
Zane19949 小时前
MVC 三层架构被打上反模式标签?一次账户扣款需求,讲清楚贫血模型和充血模型该怎么选
设计模式
geovindu1 天前
rust:Builder Pattern
开发语言·设计模式·rust·建造者模式
小王师傅661 天前
【设计模式】装饰模式(三):从装饰模式看 Java 与面向对象设计(原理篇)
设计模式
Zane19941 天前
从一次支付渠道扩展需求,看懂"多用组合少用继承"到底在说什么
设计模式
geovindu1 天前
CSharp:Condition Variable Pattern
后端·设计模式·c#·.net·.netcore·条件变量模式·同步型模式
geovindu1 天前
sql: Data Modeling Patterns using mysql
sql·mysql·设计模式·数据库开发
sarasuki2 天前
失败重试:Agent 中指数退避的正确姿势
人工智能·设计模式·agent
Zane19942 天前
为什么你写的 Java 代码"看着面向对象、实际是面向过程"?
设计模式
geovindu2 天前
sql: Data Modeling Patterns
数据库·sql·设计模式·sqlserver