设计模式学习4——装饰模式

本文深入探讨了装饰模式的概念,展示了其如何动态地给对象添加职责,提供了C#代码实例,通过装扮人物的场景,形象地解释了装饰模式的灵活性和应用。

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

定义

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

结构图

分析

装饰模式是利用Operation来对对象进行包装。这样每个装饰对象的实现和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当众。

如果只有一个ConcreteComponet类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

代码实例

为张三进行装扮,上身T恤衫,下身牛仔裤,鞋子是球鞋。

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

namespace ConsoleApplication7
{
    class Person
    {
        public Person()    { }
        private string name;

        public Person(string name)
        {
            this.name = name;
        }

        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 Tshirt : Finery
    {
        public override void Show()
        {
            Console.Write("T恤衫 ");
            base.Show();
        }
    }

    class Qiuxie : Finery
    {
        public override void Show()
        {
            Console.Write("球鞋 ");
            base.Show();
        }
    }

    class Niuzaiku : Finery
    {
        public override void Show()
        {
            Console.Write("牛仔裤 ");
            base.Show();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person ps = new Person("张三");
            Tshirt tshirt = new Tshirt();
            Qiuxie qx = new Qiuxie();
            Niuzaiku nzk = new Niuzaiku();

            tshirt.Decorate(ps);
            qx.Decorate(tshirt);
            nzk.Decorate(qx);
            nzk.Show();

            Console.ReadLine();
        }
    }
}

每个show结束后,都会运行上一层的show。此处的show即为要添加的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值