.NET 设计模式实战详解(上):创建型与结构型模式代码示例大全

一、创建型模式代码实战

1. ‌创建型模式(Creational Patterns)

核心作用‌:解决对象创建机制问题,提升代码灵活性和复用性。
包含模式‌:

  • 单例模式(Singleton)‌:确保一个类仅有一个实例。
  • 工厂方法模式(Factory Method)‌:将对象创建委托给子类。
  • 抽象工厂模式(Abstract Factory)‌:创建相关对象族,不指定具体类。
  • 建造者模式(Builder)‌:分步骤构造复杂对象。
  • 原型模式(Prototype)‌:通过克隆现有对象创建新对象。

1.1 简单工厂模式

// 支付处理器接口
public interface IPaymentProcessor
{
    void Process(decimal amount);
}

// 具体实现类
public class AlipayProcessor : IPaymentProcessor
{
    public void Process(decimal amount) 
        => Console.WriteLine($"支付宝支付:{amount}元");
}

public class WechatPayProcessor : IPaymentProcessor
{
    public void Process(decimal amount) 
        => Console.WriteLine($"微信支付:{amount}元");
}

// 简单工厂类
public class PaymentFactory
{
    public IPaymentProcessor Create(string type)
    {
        return type switch
        {
            "alipay" => new AlipayProcessor(),
            "wechat" => new WechatPayProcessor(),
            _ => throw new ArgumentException("无效的支付类型")
        };
    }
}

// 使用示例
var factory = new PaymentFactory();
var processor = factory.Create("alipay");
processor.Process(100.00m);

1.2 抽象工厂模式

// 抽象工厂接口
public interface IDatabaseFactory
{
    IConnection CreateConnection();
    ICommand CreateCommand();
}

// SQL Server实现
public class SqlServerFactory : IDatabaseFactory
{
    public IConnection CreateConnection() 
        => new SqlConnection();
    
    public ICommand CreateCommand() 
        => new SqlCommand();
}

// MySQL实现
public class MySqlFactory : IDatabaseFactory
{
    public IConnection CreateConnection() 
        => new MySqlConnection();
    
    public ICommand CreateCommand() 
        => new MySqlCommand();
}

// 使用示例
IDatabaseFactory factory = new SqlServerFactory();
var connection = factory.CreateConnection();
var command = factory.CreateCommand();

1.3 建造者模式

public class ReportBuilder
{
    private string _header = "";
    private string _body = "";
    private string _footer = "";

    public ReportBuilder AddHeader(string header)
    {
        _header = $"【{header}】\n";
        return this;
    }

    public ReportBuilder AddBody(string body)
    {
        _body = $"{body}\n";
        return this;
    }

    public ReportBuilder AddFooter(string footer)
    {
        _footer = $"——{footer}——";
        return this;
    }

    public string Build() => _header + _body + _footer;
}

// 使用示例
var report = new ReportBuilder()
    .AddHeader("2023年度报告")
    .AddBody("全年营收:1.2亿")
    .AddFooter("财务部制")
    .Build();

1.4 原型模式

public class UserProfile : ICloneable
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<string> Tags { get; set; }

    // 深拷贝实现
    public object Clone()
    {
        var clone = new UserProfile
        {
            Name = this.Name,
            Age = this.Age,
            Tags = new List<string>(this.Tags)
        };
        return clone;
    }
}

// 使用示例
var original = new UserProfile 
{ 
    Name = "张三", 
    Age = 30,
    Tags = new List<string> { "VIP", "活跃用户" }
};

var clone = (UserProfile)original.Clone();

二、结构型模式代码实战(Structural Patterns)

核心作用‌:处理类与对象的组合,形成更复杂的结构。
包含模式‌:

  • 适配器模式(Adapter)‌:让不兼容接口协同工作。
  • 桥接模式(Bridge)‌:分离抽象与实现,支持独立扩展。
  • 组合模式(Composite)‌:以树形结构处理部分-整体关系。
  • 装饰器模式(Decorator)‌:动态为对象添加职责。
  • 外观模式(Facade)‌:简化复杂子系统的访问。
  • 享元模式(Flyweight)‌:共享细粒度对象以减少内存占用。
  • 代理模式(Proxy)‌:为其他对象提供访问控制。

2.1 适配器模式

// 旧版日志接口
public interface IOldLogger
{
    void WriteLog(string message);
}

// 新版日志接口
public interface INewLogger
{
    void Log(string message, LogLevel level);
}

// 适配器实现
public class LoggerAdapter : INewLogger
{
    private readonly IOldLogger _oldLogger;

    public LoggerAdapter(IOldLogger oldLogger)
    {
        _oldLogger = oldLogger;
    }

    public void Log(string message, LogLevel level)
    {
        var formattedMsg = $"[{level}] {DateTime.Now}: {message}";
        _oldLogger.WriteLog(formattedMsg);
    }
}

2.2 装饰器模式

public interface IDataService
{
    string GetData(int id);
}

public class DatabaseService : IDataService
{
    public string GetData(int id)
        => $"原始数据:{id}";
}

public class CachingDecorator : IDataService
{
    private readonly IDataService _inner;
    private readonly Dictionary<int, string> _cache = new();

    public CachingDecorator(IDataService inner)
    {
        _inner = inner;
    }

    public string GetData(int id)
    {
        if (!_cache.ContainsKey(id))
        {
            _cache[id] = _inner.GetData(id);
        }
        return $"缓存数据:{_cache[id]}";
    }
}

// 使用示例
IDataService service = new CachingDecorator(new DatabaseService());
Console.WriteLine(service.GetData(1)); // 首次访问数据库
Console.WriteLine(service.GetData(1)); // 从缓存获取

2.3 代理模式

public interface IImageLoader
{
    void DisplayImage(string path);
}

public class RealImageLoader : IImageLoader
{
    public void DisplayImage(string path)
        => Console.WriteLine($"显示图片:{path}");
}

public class LazyImageLoader : IImageLoader
{
    private RealImageLoader _realLoader;
    private readonly string _path;

    public LazyImageLoader(string path)
    {
        _path = path;
    }

    public void DisplayImage()
    {
        _realLoader ??= new RealImageLoader();
        _realLoader.DisplayImage(_path);
    }
}

2.4 组合模式

public abstract class FileSystemItem
{
    public string Name { get; }
    public abstract void Display(int indent = 0);

    protected FileSystemItem(string name)
    {
        Name = name;
    }
}

public class FileItem : FileSystemItem
{
    public FileItem(string name) : base(name) { }

    public override void Display(int indent)
        => Console.WriteLine($"{new string(' ', indent)}📄 {Name}");
}

public class DirectoryItem : FileSystemItem
{
    private readonly List<FileSystemItem> _items = new();

    public DirectoryItem(string name) : base(name) { }

    public void Add(FileSystemItem item)
        => _items.Add(item);

    public override void Display(int indent = 0)
    {
        Console.WriteLine($"{new string(' ', indent)}📁 {Name}");
        foreach (var item in _items)
        {
            item.Display(indent + 2);
        }
    }
}

// 使用示例
var root = new DirectoryItem("根目录");
var doc = new DirectoryItem("文档");
doc.Add(new FileItem("报告.docx"));
root.Add(doc);
root.Display();

三、模式应用最佳实践

3.1 模式选择决策树

graph TD
    A[遇到问题] --> B{对象创建问题?}
    B -->|是| C[创建型模式]
    B -->|否| D{结构组织问题?}
    D -->|是| E[结构型模式]
    D -->|否| F[行为型模式]

3.2 代码质量检查清单

  • ✅ 单个类代码行数不超过200行

  • ✅ 方法参数不超过3个

  • ✅ 继承层级不超过3层

  • ✅ 代码重复率低于5%

  • ✅ 单元测试覆盖率大于80%

.NET 设计模式实战详解(下):行为型模式代码示例大全 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值