前言
策略模式: 将每个算法封装在独立的可互换的策略类中,方便在运行时选择不同的算法。
代码
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();
}
}