欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 【C#设计模式(22)——策略模式(Stratege Pattern)】

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

2025/4/25 18:26:41 来源:https://blog.csdn.net/weixin_43626218/article/details/144783279  浏览:    关键词:【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();}}

结果

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词