学习C#设计模式(九)装饰者模式

装饰者模式

using System;

namespace Decorator
{
    //抽象水果类
    public abstract class Fruit
    {
        public abstract void Plant();
    }
    public class Apple : Fruit
    {
        //种植苹果树
        public override void Plant()
        {
            Console.WriteLine("种植苹果树!");
        }
    }

    //水果抽象装饰者
    public abstract class FruitDecorator:Fruit
    {
        protected Fruit fruit;
        public FruitDecorator(Fruit fruit) 
        {
            this.fruit = fruit;
        }
        //种植水果
        public override void Plant()
        {
            if (this.fruit != null) 
            {
                this.fruit.Plant();
            }
        }
    }
    //为FruitDecorator类派生两个具体类

    //松土装饰者
    public class LoosenSoilDecorator : FruitDecorator
    {
        public LoosenSoilDecorator(Fruit fruit) : base(fruit) { }//这里base() 是调用FruitDecorator类的构造函数
        public override void Plant()
        {
            base.Plant();
            Loosen();
        }
        //为果树松土
        private void Loosen() {
            Console.WriteLine("为果树松土!");
        }
    }
    //灌溉装饰者
    public class ManureDecorator : FruitDecorator
    {
        public ManureDecorator(Fruit fruit) : base(fruit) { }//这里base() 是调用FruitDecorator类的构造函数
        public override void Plant()
        {
            base.Plant();
            Manure();
        }
        //为果树浇水
        private void Manure()
        {
            Console.WriteLine("为果树浇水!");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //创建苹果实例
            Fruit myClass = new Apple();

            //松土装饰者装饰苹果树
            LoosenSoilDecorator Loosen = new LoosenSoilDecorator(myClass);
            //灌溉装饰者装饰松土
            ManureDecorator Manure = new ManureDecorator(Loosen);

            Manure.Plant();
            Console.ReadKey();
        }
    }
}

代码解析

本实例代码实现了装饰者模式,代码中首先创建了抽象水果类Fruit,然后由该类派生出具体苹果类Apple和抽象类FruitDecorator,该类的主要作用是通过其派生类对Fruit派生的具体类的Plant方法进行装饰。FruitDecorator类中保存了Fruit对象的引用,在FruitDecorator派生类的Plant方法中,首先调用Fruit对象的Plant方法,然后调用该方法的扩展方法,实现对Plant方法的扩展。在main函数中,首先创建了Apple的实例,然后利用LoosenSoilDecorator对象对Apple实例进行装饰,接着又利用ManureDecorator对象对LoosenSoilDecorator对象进行装饰。

在装饰者模式中满足了用组合代替继承的原则,以及开放封闭原则。实例代码中FruitDecorator类与Fruit类通过组合关系来扩展Plant方法,Fruit实现了对Plant方法扩展的开放和修改的封闭。

注意:
适配器模式与装饰者模式都是对类的功能进行修改,适配器模式实现了类方法接口形式的修改而不改变其功能,而装饰者模式的目的是改变类的方法的功能而不改变方法接口的形式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值