C# 设计模式———装饰器模式

装饰器模式简介

动态地给一个对象添加一些额外的职责。就增加功能来说,它相比生成子类更为灵活。这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
在这里插入图片描述

  • Component 类充当抽象角色,不应该具体实现。
  • 修饰类引用和继承 Component 类,具体扩展类重写父类方法

一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。在不想增加很多子类的情况下扩展类。

装饰者应用了组合优于继承的思想: has - a 和 is - a 的比较;

C#装饰器模式Demo

在这里插入图片描述

using System;
namespace Decorator
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获取一个手机
            Phone phone = new ApplePhone();

            Decorate accessories = new Accessories();
            Decorate sticker = new Sticker();

            // 为手机贴膜
            sticker.SetDecorate(phone);
            // 为贴了膜的手机安装配件
            accessories.SetDecorate(sticker);

            accessories.Show();
        }
    }

    public abstract class Phone
    {
        public abstract void Show();
    }

    public class ApplePhone : Phone
    {
        public override void Show()
        {
            
            Console.WriteLine("get一个苹果手机");
        }
    }

    public class Decorate : Phone
    {
        Phone phone = null;

        public  void SetDecorate(Phone phone)
        {
            this.phone = phone;
        }
        public override void Show()
        {
            if(this.phone != null)
            {
                this.phone.Show();
            }           
        }
    }

    public class Accessories : Decorate
    {
        public override void Show()
        {
            base.Show();
            Console.WriteLine("正在进行装配......【配件】装配成功");
        }
    }

    public class Sticker : Decorate
    {
        public override void Show()
        {
            base.Show();
            Console.WriteLine("正在进行装配......【贴膜】装配成功");
        }
    }
}

测试结果:
在这里插入图片描述

C#中的装饰者模式

Stream类

Stream 含义
MemoryStream 内存流
GzipStream 压缩流
FileStream 文件流
CryptoStream 压缩流

假设有一个字节流 -> MemoryStream -> GzipStream -> FileStream -> CryptoStream

Stream stream = new MemoryStream(new byte[2] { 10, 20 });
// 压缩
stream = new GZipStream(stream, CompressionMode.Compress);
// 加密
stream = new CryptoStream(stream, null, CryptoStreamMode.Read);
总结: 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
发布了22 篇原创文章 · 获赞 20 · 访问量 2955

猜你喜欢

转载自blog.csdn.net/chasinghope/article/details/104258085