自学内容网 自学内容网

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

前言

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

代码

 //(抽象)支付策略
 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();
     }
 }

结果

在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_43626218/article/details/144783279

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!