设计模式03:行为型设计模式之策略模式的使用情景及其基础Demo

1.策略模式

  • 好处:动态切换算法或行为
  • 场景:实现同一功能用到不同的算法时
  • 和简单工厂对比:简单工厂是通过参数创建对象,调用同一个方法(实现细节不同);策略模式是上下文切换对象,调用同一个方法(实现细节不同);前者着重创建出对象,后者着重灵活切换对象。
cs 复制代码
using System;

// 01 定义通用接口
public interface IPaymentStrategy
{
    void Pay(decimal amount);
}

// 02 写接口实现策略(这里写三个) 
// 信用卡支付策略
public class CreditCardPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount:C} using Credit Card.");
    }
}

// 支付宝支付策略
public class AlipayPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount:C} using Alipay.");
    }
}

// 微信支付策略
public class WeChatPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount:C} using WeChat.");
    }
}

// 03 写上下文类,用于切换策略(内置设置策略方法、执行策略方法)
public class PaymentContext
{
    private IPaymentStrategy _paymentStrategy;

    // 构造函数
    public PaymentContext()
    {
       
    }

    // 设置或更改支付策略
    public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)
    {
        _paymentStrategy = paymentStrategy;
    }

    // 执行支付
    public void ExecutePayment(decimal amount)
    {
        _paymentStrategy.Pay(amount);
    }
}

// 04 使用:构建上下文=>上下文设置策略=>上下文执行策略
class Program
{
    static void Main(string[] args)
    {
        //构建上下文
        PaymentContext context = new PaymentContext();

        // 用户选择信用卡支付
        IPaymentStrategy creditCardPayment = new CreditCardPayment();
        context.SetPaymentStrategy(creditCardPayment);
        context.ExecutePayment(100.50m);

        // 用户更换为支付宝支付
        IPaymentStrategy alipayPayment = new AlipayPayment();
        context.SetPaymentStrategy(alipayPayment);
        context.ExecutePayment(200.75m);

        // 用户更换为微信支付
        IPaymentStrategy weChatPayment = new WeChatPayment();
        context.SetPaymentStrategy(weChatPayment);
        context.ExecutePayment(150.30m);
    }
}

2.模板方法模式

  • 好处:制定灵活的算法结构,可重写某步算法实现多种算法不同实现效果(将共同的部分提取到父类中,避免了重复代码,维护简单)
  • 场景:多种算法相似,相互有复用借鉴部分时
cs 复制代码
using System;

namespace TemplateMethodPatternDemo
{
    // 01 定义一个算法框架抽象类
    // 抽象类,定义了制作饮料的模板方法
    public abstract class Beverage
    {
        // 模板方法,定义了制作饮料的固定步骤
        public void PrepareRecipe()
        {
            BoilWater();
            BrewOrSteep();
            PourInCup();
            AddCondiments();
        }

        // 固定步骤
        private void BoilWater()
        {
            Console.WriteLine("Boiling water...");
        }

        // 抽象方法,允许子类具体实现"冲泡"或"泡制"过程
        protected abstract void BrewOrSteep();

        private void PourInCup()
        {
            Console.WriteLine("Pouring into cup...");
        }

        // 抽象方法,允许子类实现"添加调味品"步骤
        protected abstract void AddCondiments();
    }

    // 02 写不同的算法,重写父类的非公共细节(这里举例两个)
    // 具体类:制作茶
    public class Tea : Beverage
    {
        // 茶的泡制过程
        protected override void BrewOrSteep()
        {
            Console.WriteLine("Steeping the tea...");
        }

        // 添加调味品:茶通常添加柠檬
        protected override void AddCondiments()
        {
            Console.WriteLine("Adding lemon...");
        }
    }

    // 具体类:制作咖啡
    public class Coffee : Beverage
    {
        // 咖啡的冲泡过程
        protected override void BrewOrSteep()
        {
            Console.WriteLine("Brewing the coffee...");
        }

        // 添加调味品:咖啡通常添加糖和牛奶
        protected override void AddCondiments()
        {
            Console.WriteLine("Adding sugar and milk...");
        }
    }

    // 03 根据不同对象调用,实现不一样的算法
    // 客户端代码
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Making Tea...");
            Beverage tea = new Tea();
            tea.PrepareRecipe(); // 调用模板方法

            Console.WriteLine();

            Console.WriteLine("Making Coffee...");
            Beverage coffee = new Coffee();
            coffee.PrepareRecipe(); // 调用模板方法
        }
    }
}
相关推荐
晚安code1 小时前
设计模式入门:吃透 SOLID 原则与迪米特法则,再学 5 个高频模式
后端·设计模式
染指11105 小时前
135.Agent-多Agent框架-LangChain多智能体(SubAgents子代理)
数据库·人工智能·设计模式·langchain·agent·agents
路弥行至1 天前
【Head First 设计模式】第 2 章:观察者模式 —— 用现代 C++ 重新解读“交互对象的松耦合
c++·经验分享·笔记·观察者模式·设计模式·入门教程·headfirst
YYYing.1 天前
【设计模式系列 (九) 】装饰器模式
c++·后端·设计模式·装饰器模式·c/c++
沫璃染墨1 天前
《从零入门Linux系统篇(五十六):线程篇·九——生产者消费者模型:从条件变量到BlockingQueue实现》
linux·服务器·c++·驱动开发·设计模式·架构·系统架构
c萱2 天前
AI产品经理——01基础认知篇
设计模式·prompt·aigc·产品经理·ai编程·gitcode·ai-native
蜗牛互联网2 天前
Computer Use公共预览的安全设计:应用、动作与数据三维门禁
java·人工智能·后端·安全·策略模式
YYYing.2 天前
【设计模式系列 (八) 】组合模式
c++·后端·设计模式·组合模式·c/c++
geovindu3 天前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
今年下半年3 天前
【Spring Boot】多种存储文件(FastDFS / MinIO / 阿里云 OSS)接入设计说明(附源码)
spring boot·分布式·中间件·简单工厂模式·策略模式