一、什么是策略模式
它是一个行为型设计模式,简单来说这个模式就是将相似的东西封装一下,跟之前一样,再包一层。
二、策略模式的作用
应对业务处理中,会有多种相似处理方式,然后封闭成算法+抽象。
三、策略模式的使用场景
比如商品打折会有多种不同的算法,在不同的时候,打折的算法就不相同,而且随时有可能需要新增算法,我们就可以使用策略模式,因为都是传一个值进去,然后输出折扣后的价格,中间是怎么计算的,哪就是不同算法内的事了,在使用这些算法步骤都是一样的。
四、如何实现策略模式
这里就直接写最终极的版本。
主程序:
namespace Strategy
{
class Program
{
static void Main(string[] args)
{
try
{
float iResult = 0;
float iPrice = 99.99f;
IDiscount iDiscount = null;
iDiscount = DiscountFactory.GetDiscount();
DiscountContext context = new DiscountContext(iDiscount, iPrice);
iResult = context.Action();
Console.WriteLine($"原价:{iPrice},折后价:{iResult}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
折扣算法工厂DiscountFactory.cs:
namespace Strategy
{
public class DiscountFactory
{
public static IDiscount GetDiscount()
{
string key = ConfigurationManager.AppSettings["IDiscountName"];
string dllType = ConfigurationManager.AppSettings[key];
Assembly assembly = Assembly.Load(dllType.Split(',')[0]);
Type type = assembly.GetType(dllType.Split(',')[1]);
return (IDiscount)Activator.CreateInstance(type);
}
}
}
配置文件:
<appSettings>
<add key="IDiscountName" value="DiscountTwo"/>
<add key="DiscountOne" value="Strategy.Service,Strategy.Service.DiscountOne"/>
<add key="DiscountTwo" value="Strategy.Service,Strategy.Service.DiscountTwo"/>
</appSettings>
折扣算法上下文DiscountContext.cs:
namespace Strategy
{
public class DiscountContext
{
private IDiscount _iDiscount = null;
private float _iPrice = 0;
public DiscountContext(IDiscount discount, float iPrice)
{
this._iDiscount = discount;
this._iPrice = iPrice;
}
public float Action()
{
try
{
return this._iDiscount.Calculation(this._iPrice);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
算法接口IDiscount.cs:
namespace Strategy.Interface
{
public interface IDiscount
{
float Calculation(float iPrice);
}
}
具体算法类:
//DiscountOne.cs
namespace Strategy.Service
{
public class DiscountOne : IDiscount
{
public float Calculation(float iPrice)
{
Console.WriteLine($"折扣算法:{this.GetType().Name}");
return iPrice * 0.9f;
}
}
}
//DiscountTwo.cs
namespace Strategy.Service
{
public class DiscountTwo : IDiscount
{
public float Calculation(float iPrice)
{
Console.WriteLine($"折扣算法:{this.GetType().Name}");
return iPrice * 0.5f;
}
}
}
以上为本章所有内容。
完。