设计模式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(); // 调用模板方法
        }
    }
}
相关推荐
会员果汁1 小时前
14.设计模式-备忘录模式
设计模式·备忘录模式
有个人神神叨叨1 小时前
AITalk:从零到一打造 macOS 系统级语音输入引擎
macos·策略模式
xiaolyuh12311 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
GISer_Jing1 天前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing1 天前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌1 天前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁1 天前
12.设计模式-状态模式
设计模式·状态模式
且去填词1 天前
DeepSeek :基于 AST 与 AI 的遗留系统“手术刀”式治理方案
人工智能·自动化·llm·ast·agent·策略模式·deepseek
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式