【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 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder12 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室19 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的4 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21884 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi4 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice