C#编程模式之装饰模式

        创作背景:朋友们,我们继续C#编程模式的学习,本文我们将一起探讨装饰模式。装饰模式也是一种结构型设计模式,它允许你通过在运行时向对象添加额外的功能,从而动态的修改对象的行为。装饰模式本质上还是继承的一种替换方式,通过组合的形式来扩展对象的功能。

        使用场景:当我们不想使用继承来扩展功能的时候,或者我们希望在运行时动态地添加功能的时候,再或者我们想要通过组合的形式来使对象获取更大的灵活性的时候,都可以使用装饰模式。

        优劣分析:1、能灵活的扩展对象的功能,避免类似功能的类的增加;2、不易过多使用,否则程序将难以理解,而且每装饰一次,都会增加一个对象。

        程序实现:

        1、创建一个组件接口。

    /// <summary>
    /// 对象接口,其功能是动态的给对象添加新属性或者功能。
    /// </summary>
    public abstract class ComponentDec
    {
        public abstract string Operation();
    }

        2、实现具体的组件。

    /// <summary>
    /// 定义一个对象,可以给这个对象添加一些职责
    /// </summary>
    public class ConcreteComponentDec : ComponentDec
    {
        public override string Operation()
        {
            string strResult = string.Empty;
            strResult = "创建一个对象";

            return strResult;
        }
    }

        3、创建装饰器抽象类。

    /// <summary>
    /// 维持一个指向Component的指针,并定义一个与Component接口一致的接口
    /// </summary>
    public abstract class DecoratorDec : ComponentDec
    {
        protected ComponentDec componentDec;

        public void SetComponent(ComponentDec componentDec)
        {
            this.componentDec = componentDec;
        }

        public override string Operation()
        {
            if (componentDec != null)
            {
                return componentDec.Operation();
            }

            return string.Empty;
        }
    }

        4、具体的装饰器。

    /// <summary>
    /// 具体的装饰器A
    /// </summary>
    public class ConcreteDecoratorA : DecoratorDec
    {
        public override string Operation()
        {
            return AddedBehavior() + base.Operation();
        }

        private string AddedBehavior()
        {
            return "我是A,";
        }
    }


    /// <summary>
    /// 具体的装饰器B
    /// </summary>
    public class ConcreteDecoratorB : DecoratorDec
    {
        public override string Operation()
        {
            return AddedBehavior() + base.Operation();
        }

        private string AddedBehavior()
        {
            return "我是B,";
        }
    }

        5、客户端调用结果。

        各位朋友,以上就是小编关于装饰模式的理解。希望各路大神批评指正。 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值