定义: 策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。
优点: 1、算法可以自由切换。 2、避免使用多重条件判断。 3、扩展性良好。
缺点: 1、策略类会增多。 2、所有策略类都需要对外暴露。
cs
namespace ConsoleApp1
{
//定义抽象策略
public interface IStrategy
{
float calc(int num1, int num2);
}
//定义具体策略
//加法
public class AddStrategy : IStrategy
{
public float calc(int num1, int num2)
{
return num1 + num2;
}
}
//减法
public class SubstractStrategy : IStrategy
{
public float calc(int num1, int num2)
{
return num1 - num2;
}
}
//乘法
public class MultiplicationStrategy : IStrategy
{
public float calc(int num1, int num2)
{
return num1 * num2;
}
}
//除法
public class DivisionStrategy : IStrategy
{
public float calc(int num1, int num2)
{
return num1 / num2;
}
}
//处理环境
public class Environment
{
private IStrategy strategy;
public Environment(IStrategy strategy)
{
this.strategy = strategy;
}
public float calculate(int a, int b)
{
return strategy.calc(a, b);
}
}
class Program
{
static void Main(string[] args)
{
Environment environment = new Environment(new AddStrategy());
float result = environment.calculate(20, 5);
Console.WriteLine("计算结果:" + result);
Environment environment1 = new Environment(new SubstractStrategy());
float result1 = environment1.calculate(20, 5);
Console.WriteLine("计算结果:" + result1);
Environment environment2 = new Environment(new MultiplicationStrategy());
float result2 = environment2.calculate(20, 5);
Console.WriteLine("计算结果:" + result2);
Environment environment3 = new Environment(new DivisionStrategy());
float result3 = environment3.calculate(20, 5);
Console.WriteLine("计算结果:" + result3);
}
}
}