策略模式:定义一系列的算法,将每个算法分别封装起来,让它们可以互相替换。
策略模式用于算法的自由切换和扩展,它是使用较为广泛的设计模式之一。策略模式对应于解决某一问题的一个算法族,允许用户从该算法中任选一个算法解决某一问题,同时可以方便地更换算法或者增加新算法。
策略模式实现了算法定义和算法使用分离,它通过继承和多态的机制实现对算法族的使用和管理,是一个简单实用的设计模式。
//以下使用的是顶级语句
//未使用依赖注入的调用
//var ef = new EFCoreRepository();
//var redis = new RedisRepostitory();
//var appService = new AppService(redis);
//appService.Create(null);
//使用依赖注入的调用
using Microsoft.Extensions.DependencyInjection;
var services=new ServiceCollection(); //服务容器,依赖注入容器,IoC控制反转
services.AddScoped<IRepository,EFCoreRepository>();//添加作用域
//services.AddScoped<IRepository, RedisRepostitory>();//添加作用域
services.AddScoped<AppService>();
var builder=services.BuildServiceProvider();//生成服务提供程序
var appService=builder.GetRequiredService<AppService>();//获取所需服务
appService.Create(null);
public class EFCoreRepository : IRepository //EF仓储
{
public void Add(object entity)
{
Console.WriteLine("EF Core的仓储");
}
}
public class RedisRepostitory : IRepository
{
public void Add(object entity)
{
Console.WriteLine("Redis的仓储");
}
}
public interface IRepository //仓储
{
void Add(object entity);
}
class AppService
{
private readonly IRepository _repository;
public AppService(IRepository repository)
{
this._repository = repository;
}
public void Create(object entity)
{
_repository.Add(entity);
}
}
下面是一个电影票根据不同用户类型打折的实例
using Microsoft.Extensions.DependencyInjection;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
var service = new ServiceCollection();
service.AddScoped<IStrategy, StudentStrategy>()
.AddScoped<AppService>();
var builder = service.BuildServiceProvider();
var appSerivce=builder.GetRequiredService<AppService>();
appSerivce.Price = 50;
Console.WriteLine("电影票原价50元");
Console.WriteLine(appSerivce.Price);
class StudentStrategy : IStrategy
{
readonly string _name = "学生";
readonly Double _discount = 0.8;
public decimal Calculate(decimal price)
{
Console.WriteLine(_name + "票:");
return price * (decimal)_discount;
}
}
class ChildrenStrategy : IStrategy
{
readonly string _name = "儿童";
readonly Double _discount = 10;
public decimal Calculate(decimal price)
{
Console.WriteLine(_name + "票:");
return price * (decimal)_discount;
}
}
class VIPStrategy : IStrategy
{
readonly string _name = "VIP";
readonly Double _discount = 0.5;
public decimal Calculate(decimal price)
{
Console.WriteLine(_name + "票:");
return price * (decimal)_discount;
}
}
/// <summary>
/// 算法策略接口
/// </summary>
public interface IStrategy
{
decimal Calculate(decimal price);
}
public class AppService
{
private decimal _price;
private readonly IStrategy _strategy;
public AppService(IStrategy strategy)
{
_strategy = strategy;
}
public decimal Price
{
get => _strategy.Calculate(_price);
set => _price = value;
}
}
标签:策略,price,readonly,模式,public,算法,var,设计模式,decimal
From: https://www.cnblogs.com/bcd589/p/17810274.html