【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();
     }
 }

结果

相关推荐
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹1 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
kybs19911 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
Zane19941 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
Polevne1 天前
C# SFTP客户端实现文件传输
c#·ssh
samble1 天前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5601 天前
024 . WPF MVVM类封装优化
c#
淡海水2 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx672 天前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707782 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel