【C#设计模式(22)——策略模式(Stratege Pattern)】

前言

策略模式: 将每个算法封装在独立的可互换的策略类中,方便在运行时选择不同的算法。

代码

csharp 复制代码
 //(抽象)支付策略
 public abstract class PaymentStrategy
 {
     public abstract void Play(double amount);
 }
 //支付策略: 银行卡支付
 public class BankCardPayment : PaymentStrategy
 {
     private string account = "6222800421153124288";
     private string password = "123456";
     public BankCardPayment(string account, string password)
     {
         this.account = account;
         this.password = password;
     }
     public override void Play(double amount)
     {
         Console.WriteLine($"You used your bank card account {account} to pay ${amount}.");
     }
 }
 //支付策略: 微信支付
 public class WeChatPayment : PaymentStrategy
 {
     private string username = "user1";
     private string password = "123456";

     public WeChatPayment(string username, string password)
     {
         this.username = username;
         this.password = password;
     }
     public override void Play(double amount)
     {
         Console.WriteLine($"You used your  WeChat account  {username}  to pay ${amount}.");
     }
 }
 //支付环境: 购物车
 public class ShoppingCart
 {
     private PaymentStrategy paymentStrategy;

     public void SetPaymentStrategy(PaymentStrategy paymentStrategy)
     {
         this.paymentStrategy = paymentStrategy;
     }
     public void CheckOut(double amount)
     {
         paymentStrategy.Play(amount);
     }

 }

 /*
  * 行为型模式:Behavioral Pattern
  * 策略模式:Stratege Pattern
  */
 internal class Program
 {
     static void Main(string[] args)
     {
         ShoppingCart cart = new ShoppingCart();

         PaymentStrategy bankPay = new BankCardPayment("6222800421153000000","123456");
         cart.SetPaymentStrategy(bankPay);
         cart.CheckOut(10000);

         PaymentStrategy wechatPay = new WeChatPayment("asdfghjkl", "123456");
         cart.SetPaymentStrategy(wechatPay);
         cart.CheckOut(890.5);

         Console.ReadLine();
     }
 }

结果

相关推荐
拆房老料12 小时前
DeepSeek Super-agent 架构解析:从单任务 Agent 到持续运行的任务系统
人工智能·设计模式·系统架构
AlanAshley13 小时前
四种镜像文件在各操作系统的使用用法及区别
策略模式·虚拟机
淡海水14 小时前
10-01-互操作-C#与C++边界的内存管理
unity·c#·游戏引擎·.netcore·gc
WarPigs16 小时前
C#把byte[]以十六进制打印,带分割符
c#
工一木子17 小时前
设计模式与生活⑩:地铁没变,你换了个状态
设计模式
暴走约伯17 小时前
【VFX工具链源码拆解 04】拯救丢失的绑定:Timeline 一键克隆与层级相对路径重映射算法
unity·c#·游戏引擎·硬件工程
1-1=017 小时前
C# 反射
c#·.net·.netcore
步步为营DotNet19 小时前
.NET 可观测性选型:Metrics、ActivitySource、EventSource 到底该用哪个
c#·.net·metrics·可观测性
是2的10次方啊19 小时前
设计模式与生活⑪:地铁里被打扰,别总靠自己硬扛
设计模式
吃一碗粉只付一碗钱1 天前
16-SqlSugar多库ConfigId与按实体选连接
sqlserver·c#