大话设计模式 - 装饰模式

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

摘要生成于 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中.
这样循环嵌套, 就可以实现按照一定顺序添加功能的目的.**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值