【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 天前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
o0向阳而生0o1 天前
100、23种设计模式之适配器模式(9/23)
设计模式·适配器模式
将编程培养成爱好1 天前
C++ 设计模式《外卖菜单展示》
c++·设计模式
特种加菲猫1 天前
并发编程的守护者:信号量与日志策略模式解析
linux·笔记·策略模式
TechNomad2 天前
设计模式:状态模式(State Pattern)
设计模式·状态模式
努力也学不会java2 天前
【设计模式】 原型模式
java·设计模式·原型模式
TechNomad2 天前
设计模式:模板方法模式(Template Method Pattern)
设计模式·模板方法模式
leo03082 天前
7种流行Prompt设计模式详解:适用场景与最佳实践
设计模式·prompt
xiaowu0802 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
ytadpole2 天前
揭秘设计模式:工厂模式的五级进化之路
java·设计模式