设计模式之策略模式的实现
策略模式通用UML类图 with StarUML
具体实现的UML类图 with StarUML
折扣接口
namespace StrategyPattern
{
interface Discount
{
double Calculate(double price);
}
}
学生折扣类
namespace StrategyPattern
{
internal class StudentDiscount:Discount
{
private const double DISCOUNT = 0.8;
public double Calculate(double price)
{
Console.WriteLine("学生票:");
return price * DISCOUNT;
}
}
}
儿童折扣类
namespace StrategyPattern
{
internal class ChildrenDiscount : Discount
{
private const double DISCOUNT = 10;
public double Calculate(double price)
{
Console.WriteLine("儿童票:");
return price - DISCOUNT;
}
}
}
VIP折扣类
namespace StrategyPattern
{
internal class VIPDiscount : Discount
{
private const double DISCOUNT = 0.5;
public double Calculate(double price)
{
Console.WriteLine("VIP票:");
Console.WriteLine("增加积分!");
return price * DISCOUNT;
}
}
}
电影票类
namespace StrategyPattern
{
internal class MovieTicket
{
private double price;
private Discount discount;
public void SetDiscount(Discount discount)
{
this.discount = discount;
}
public double Price
{
get { return discount.Calculate(this.price); }
set { price = value; }
}
}
}
XML配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="discountType" value="StrategyPattern.ChildrenDiscount"/>
</appSettings>
</configuration>
测试代码
namespace StrategyPattern
{
internal class Program
{
static void Main(string[] args)
{
MovieTicket mt = new MovieTicket();
double originalPrice = 60;
double currentPrice;
mt.Price = originalPrice;
Console.WriteLine($"原始价为:{originalPrice}");
Console.WriteLine("---------------------------------");
Discount discount;
string discountType = ConfigurationManager.AppSettings["discountType"];
discount = (Discount)Assembly.Load("StrategyPattern").CreateInstance(discountType);
mt.SetDiscount(discount);
currentPrice = mt.Price;
Console.WriteLine($"折后价为:{currentPrice}");
Console.Read();
}
}
}
执行结果