23种设计模式(20):装饰模式

概述:

动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

类型:结构型模式。

类图:

适用性:

1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。

2.处理那些可以撤消的职责。

3.当不能采用生成子类的方法进行扩充时。

参与者:

1.Component

定义一个对象接口,可以给这些对象动态地添加职责。

2.ConcreteComponent

定义一个对象,可以给这个对象添加一些职责。

3.Decorator

维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。

4.ConcreteDecorator

向组件添加职责。

例子:


Component 

public interface Person {



    void eat();

}

ConcreteComponent 

public class Man implements Person {



    public void eat() {

        System.out.println("男人在吃");

    }

}

Decorator 

public abstract class Decorator implements Person {



    protected Person person;



    public void setPerson(Person person) {

        this.person = person;

    }



    public void eat() {

        person.eat();

    }

}

ConcreteDecorator 

public class ManDecoratorA extends Decorator {



    public void eat() {

        super.eat();

        reEat();

        System.out.println("ManDecoratorA类");

    }



    public void reEat() {

        System.out.println("再吃一顿饭");

    }

}

public class ManDecoratorB extends Decorator {



    public void eat() {

        super.eat();

        System.out.println("===============");

        System.out.println("ManDecoratorB类");

    }

}

Test 

public class Test {



    public static void main(String[] args) {

        Man man = new Man();

        ManDecoratorA md1 = new ManDecoratorA();

        ManDecoratorB md2 = new ManDecoratorB();



        md1.setPerson(man);

        md2.setPerson(md1);

        md2.eat();

    }

}

result:


男人在吃

再吃一顿饭

ManDecoratorA类

===============

ManDecoratorB类
posted @   尐鱼儿  阅读(113)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示