📅 Day 24:设计模式入门(Design Patterns in C#)
✅ 学习目标:
- 理解什么是 设计模式(Design Pattern);
- 掌握设计模式的分类(创建型、结构型、行为型);
- 理解常见设计模式的基本原理和使用场景;
- 学会实现几种最常用的设计模式,如:
- 单例模式(Singleton)
- 工厂模式(Factory / Abstract Factory)
- 策略模式(Strategy)
- 能够在实际项目中识别并合理应用设计模式;
- 编写一个结合多个设计模式的示例程序(如支付系统模拟器)。
🧠 一、什么是设计模式?
设计模式(Design Pattern) 是软件开发中一些被广泛认可的、可复用的解决方案模板。它们不是具体的代码,而是一种描述如何组织类和对象来解决特定问题的“套路”。
设计模式 ≠ 框架或库,而是面向对象设计经验的总结。
📘 二、设计模式的三大分类
类别 | 模式举例 | 功能 |
---|---|---|
创建型(Creational) | 单例、工厂、建造者 | 控制对象的创建方式 |
结构型(Structural) | 适配器、装饰器、代理 | 对象与类的组合方式 |
行为型(Behavioral) | 观察者、策略、命令 | 对象之间的交互与职责分配 |
🔨 三、常用设计模式详解与示例
1️⃣ 单例模式(Singleton Pattern)
用途:确保一个类只有一个实例,并提供全局访问点。
public sealed class Logger
{private static readonly Logger _instance = new Logger();private Logger() { }public static Logger Instance => _instance;public void Log(string message){Console.WriteLine("日志:" + message);}
}
使用:
Logger.Instance.Log("应用程序启动");
✅ 适用场景:日志记录器、数据库连接池、配置管理等。
2️⃣ 工厂模式(Factory Pattern)
用途:将对象的创建逻辑封装到一个类中,调用者无需关心具体类型。
public interface IPaymentProcessor
{void ProcessPayment(decimal amount);
}public class CreditCardProcessor : IPaymentProcessor
{public void ProcessPayment(decimal amount){Console.WriteLine($"信用卡支付:{amount:C}");}
}public class PayPalProcessor : IPaymentProcessor
{public void ProcessPayment(decimal amount){Console.WriteLine($"PayPal 支付:{amount:C}");}
}public class PaymentFactory
{public IPaymentProcessor GetProcessor(string type){return type.ToLower() switch{"creditcard" => new CreditCardProcessor(),"paypal" => new PayPalProcessor(),_ => throw new ArgumentException("不支持的支付方式"),};}
}
使用:
var factory = new PaymentFactory();
IPaymentProcessor processor = factory.GetProcessor("paypal");
processor.ProcessPayment(100.00m);
✅ 适用场景:根据条件动态选择不同实现、统一接口暴露。
3️⃣ 抽象工厂模式(Abstract Factory Pattern)
用途:用于创建一组相关或依赖对象家族,适用于多平台/多品牌产品线。
示例:创建 Windows 和 Mac 风格的 UI 控件。
public interface IButton
{void Render();
}public class WindowsButton : IButton
{public void Render() => Console.WriteLine("渲染 Windows 按钮");
}public class MacButton : IButton
{public void Render() => Console.WriteLine("渲染 macOS 按钮");
}public interface IUIFactory
{IButton CreateButton();
}public class WindowsFactory : IUIFactory
{public IButton CreateButton() => new WindowsButton();
}public class MacFactory : IUIFactory
{public IButton CreateButton() => new MacButton();
}
使用:
IUIFactory factory = new MacFactory();
IButton button = factory.CreateButton();
button.Render(); // 输出:渲染 macOS 按钮
✅ 适用场景:跨平台 UI、产品族构建、系统抽象层。
4️⃣ 策略模式(Strategy Pattern)
用途:定义一系列算法,把它们一个个封装起来,并使它们可以互相替换。
public interface IDiscountStrategy
{decimal ApplyDiscount(decimal price);
}public class NoDiscount : IDiscountStrategy
{public decimal ApplyDiscount(decimal price) => price;
}public class TenPercentDiscount : IDiscountStrategy
{public decimal ApplyDiscount(decimal price) => price * 0.9m;
}public class FiftyPercentDiscount : IDiscountStrategy
{public decimal ApplyDiscount(decimal price) => price * 0.5m;
}public class ShoppingCart
{public IDiscountStrategy DiscountStrategy { get; set; }public decimal Checkout(decimal totalPrice){return DiscountStrategy.ApplyDiscount(totalPrice);}
}
使用:
var cart = new ShoppingCart();
cart.DiscountStrategy = new TenPercentDiscount();
decimal finalPrice = cart.Checkout(100m); // 最终价格:90.00
✅ 适用场景:促销活动、支付方式、排序算法切换等。
💡 四、设计模式选择指南(简单对照)
场景 | 推荐模式 |
---|---|
创建唯一对象 | 单例 |
根据条件创建不同类型对象 | 工厂 |
多个相关类一起创建 | 抽象工厂 |
替换算法或行为 | 策略 |
扩展功能而不修改原类 | 装饰器 |
对象间通信解耦 | 观察者 |
延迟初始化 | 代理 |
💪 实战练习:支付系统模拟器
功能要求:
- 用户可以选择不同的支付方式(信用卡、PayPal);
- 可以应用不同的折扣策略(无折扣、10% 折扣、50% 折扣);
- 使用工厂模式创建支付处理器;
- 使用策略模式应用折扣;
- 输出最终支付金额。
示例代码框架:
class Program
{static void Main(){var paymentFactory = new PaymentFactory();var discountStrategy = new TenPercentDiscount();IPaymentProcessor processor = paymentFactory.GetProcessor("creditcard");var cart = new ShoppingCart(discountStrategy);decimal total = cart.Checkout(200.00m);processor.ProcessPayment(total);}
}
📝 小结
今天你学会了:
- 什么是设计模式及其分类;
- 掌握了 单例模式、工厂模式、抽象工厂模式、策略模式 的基本概念和实现;
- 理解了每种模式的典型应用场景;
- 编写了一个结合多种设计模式的支付系统模拟器;
- 学会了如何在实际项目中识别并合理使用设计模式。
设计模式是编写高质量、可维护、易扩展代码的重要工具。掌握它们不仅能提升你的架构能力,也能让你更好地理解和阅读大型开源项目的源码。
🧩 下一步学习方向(Day 25)
明天我们将进入一个新的主题 —— 高级设计模式与 SOLID 原则实践,你将学会如何结合 SOLID 原则使用更复杂的设计模式,如观察者、装饰器、责任链、命令等,并构建模块化、可测试性强的应用程序架构。