大话设计模式 - 装饰模式

本文介绍了一种装饰模式的具体实现方式,通过将多个装饰功能置于独立的类中,并以递归的方式包装目标对象,实现了动态地为对象添加职责的能力。文章通过一个具体的服饰装扮示例,展示了如何使用装饰模式来灵活地添加和组合对象的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰模式把每个要装饰的功能放在单独的类中, 并让这个类包装他所要装饰的对象. 因此, 当需要执行特殊行为时, 客户代码可以在运行时根据需要有选择地按顺序地使用装饰功能包装对象了.

这里写图片描述

服饰装扮代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DecorateMode
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("小明");

            Sneakers sk = new Sneakers();
            BigTrouser bt = new BigTrouser();
            TShirts ts = new TShirts();

            sk.Decorate(p);
            sk.Show();
            bt.Decorate(sk);
            bt.Show();
            ts.Decorate(bt);
            ts.Show();
        }
    }
    // person virtual
    class Person
    {
        public Person()
        {}
        private string name;
        public Person(string name)
        {
            this.name = name;
        }
        // 注意是virtual. 子类可以重写也可以不重写. Person可以实例化.
        public virtual void Show()
        {
            Console.WriteLine(" 装扮的{0}", name);
        }
    }
    // 服饰 
    class Finery : Person 
    {
        protected Person component;
        //
        public void Decorate(Person component)
        {
            this.component = component;
        }

        public override void Show()
        {
            if(component !=null)
            {
                component.Show();
            }
        }
    }
    class TShirts : Finery
    {
        public override void Show()
        {
            Console.Write(" T-Shirt ");
            base.Show();
        }
    }
    class BigTrouser : Finery
    {
        public override void Show()
        {
            Console.Write(" big trousers ");
            base.Show();
        }
    }
    class Sneakers : Finery
    {
        public override void Show()
        {
            Console.Write(" Sneakers ");
            base.Show();
        }
    }
    class LeatherShoes : Finery
    {
        public override void Show()
        {
            Console.Write("LeatherShoes");
            base.Show();
        }
    }
    class Tie : Finery
    {
        public override void Show()
        {
            Console.Write("Tie");
            base.Show();
        }
    }
    class Suit : Finery
    {
        public override void Show()
        {
            Console.Write("Suit");
            base.Show();
        }
    }
}

输出结果:
这里写图片描述
**装饰类对象Finery里面有一个父类Person对象component.
父类show是virtual. 可以实现多态.
所以. Finery的子类可以将其他Finery的子类包装在自己的component中.
这样循环嵌套, 就可以实现按照一定顺序添加功能的目的.**

### C++ 中装饰模式的设计与实现 #### 装饰模式概述 装饰模式是一种结构型设计模式,允许在运行时动态地给对象添加行为和责任。这种模式提供了比静态继承更灵活的方式来扩展功能[^2]。 #### 关键组件说明 - **抽象构件 (Component)** 定义了一个接口或抽象类,用于声明所有具体构件以及装饰器共同的操作方法。所有具体的构件和装饰器都将基于此接口工作[^4]。 - **具体构件 (Concrete Component)** 实现了由`Component`定义的接口,代表基本的对象实例,在不附加任何额外的行为下完成特定的任务。 - **抽象装饰 (Decorator)** 继承自`Component`的同时也持有一个指向`Component`类型的成员变量。它不仅能够代理原有对象的方法调用,还可以在此基础上加入新的逻辑处理。 - **具体装饰 (Concrete Decorator)** 扩展了`Decorator`的功能,通过重载某些方法来改变原对象的行为或是为其增添新特性。每一个具体的装饰者都可以独立存在,并且可以相互叠加使用以达到累积的效果。 #### 示例代码展示 下面是一个简单的C++程序展示了如何利用装饰模式为文本字符串加上不同风格的边框: ```cpp #include <iostream> #include <string> // 抽象构件:定义一个通用接口 class Shape { public: virtual void draw() const = 0; }; // 具体构件:实现了Shape接口的一个简单矩形形状 class Rectangle : public Shape { public: void draw() const override { std::cout << "Drawing a rectangle." << std::endl; } }; // 抽象装饰:持有对另一个Shape对象的引用 class BorderDecorator : public Shape { protected: Shape* shape; public: explicit BorderDecorator(Shape* s) : shape(s) {} ~BorderDecorator() override { delete shape; } void draw() const override { shape->draw(); } // 默认只是转发请求给内部持有的shape对象 }; // 具体装饰A:为图形添加虚线边框 class DashedBorderDecorator : public BorderDecorator { public: using BorderDecorator::BorderDecorator; void draw() const override { std::cout << "Adding dashed border..." << std::endl; BorderDecorator::draw(); } }; // 具体装饰B:为图形添加实心边框 class SolidBorderDecorator : public BorderDecorator { public: using BorderDecorator::BorderDecorator; void draw() const override { std::cout << "Adding solid border..." << std::endl; BorderDecorator::draw(); } }; int main(){ auto *rectangle = new Rectangle(); // 可以自由组合不同的装饰层 auto *dashed_rectangle = new DashedBorderDecorator(rectangle); auto *solid_dashed_rectangle = new SolidBorderDecorator(dashed_rectangle); solid_dashed_rectangle->draw(); delete solid_dashed_rectangle; return 0; } ``` 在这个例子中,`Rectangle`作为最基础的具体构件;而`DashedBorderDecorator` 和 `SolidBorderDecorator` 则分别扮演着两种不同类型的具体装饰角色。它们可以在不影响其他部分的情况下轻松地被应用到任意数量的不同形状上[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值