关于策略模式下需要用到一个接口多个实现的方案
https://www.jianshu.com/p/0753de68244c
此链接是策略模式的案例,讲述多个优惠策略实现同一个接口的应用场景
我们需要用到DI的高级玩法:
在接口定义方法标识
优惠策略接口抽象出一个方法Get() 获取优惠,优惠的实现有很多,我们需要在Startup注入所有的优惠策略的实现
public interface IActivitiesStrategy
{
string Realize { get; }
/// <summary>
/// 获取则扣策略
/// </summary>
/// <returns></returns>
double GetDiscountStrategy();
}
在优惠策略的具体实现上写出方法标识
public class DoubleElevenActivities : IActivitiesStrategy
{
public string Realize => "双十一优惠";
public double GetDiscountStrategy()
{
return 0.11;
}
}
public class DoubleTwelveActivities : IActivitiesStrategy
{
public string Realize => "双十二优惠";
public double GetDiscountStrategy()
{
return 0.12;
}
}
注册所有方法
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IActivitiesStrategy, DoubleElevenActivities>();
services.AddTransient<IActivitiesStrategy, DoubleTwelveActivities>();
services.AddMvc();
}
在使用时候判断使用什么策略
public class ValuesController : ControllerBase
{
private readonly IEnumerable<IActivitiesStrategy> _activitiesStrategy;
public ValuesController(IEnumerable<IActivitiesStrategy> activitiesStrategy)
{
_activitiesStrategy = activitiesStrategy;
}
// GET api/values
[HttpGet]
public ActionResult<double> Get(string tag)
{
var method = _activitiesStrategy.Where(x => x.Realize == tag).FirstOrDefault();
if (method != null)
{
return method.GetDiscountStrategy();
}
return 1;
}
}
网友评论