一:动机(Motivation)
<1>在软件构建过程中,某些对象使用的算法可能多种多样,经常改变,如果将这些算法都编码到对象中,将会使对象变得异常复杂;而且有时候支持不使用的算法也是一个性能负担。
<2>如何在运行时根据需要透明地更改对象的算法?将算法与对象本身解耦,从而避免上述问题?
二:意图(Intent)
定义一系列算法,把它们一个个封装起来,并且使它们可互相替换。该模式使得算法可独立于使用它的客户而变化。
——《设计模式》GoF
三:结构(Structure)
四:结构详解
五:生活中的例子
超市购物,根据总价有不同的优惠策略:
不折扣现金,要赠品
满300元送100元
打8折
……….
六:实现
namespace Test
{
/// <summary>
/// Strategy策略
/// </summary>
public abstract class 优惠策略
{
//algorithmInterface算法定义
public abstract double 计算优惠(double 总价);
}
public class 要赠品 : 优惠策略
{
public override double 计算优惠(double 总价)
{
Console.WriteLine("不折扣现金,要赠品:送一个玩具狗熊!");
return 总价;
}
}
public class 打八折 : 优惠策略
{
public override double 计算优惠(double 总价)
{
Console.WriteLine("打八折!");
return 总价 * 0.8;
}
}
public class 返现金 : 优惠策略
{
public override double 计算优惠(double 总价)
{
Console.WriteLine("满300元减100!");
if (总价 >= 300)
{
return 总价 - 100;
}
else
{
return 总价;
}
}
}
public class 顾客
{
private double total;
public 顾客(double 总价)
{
this.total = 总价;
}
public void 使用优惠(优惠策略 strategy)
{
double 实价 = 0;
实价 = strategy.计算优惠(this.total);
Console.WriteLine("本次优惠后,实际价格为:{0}\n", 实价);
}
}
internal class Program
{
static void Main(string[] args)
{
double 总价 = 1000;
优惠策略 strategy;
顾客 customer = new 顾客(总价);
strategy = new 要赠品();
customer.使用优惠(strategy);
strategy = new 返现金();
customer.使用优惠(strategy);
strategy = new 打八折();
customer.使用优惠(strategy);
Console.ReadLine();
}
}
}
实现结果
七:实现要点
<1>使用的过程中,必须要”知道”具体的策略类,耦合性高;
<2>抽象类到具体类的实例化过程还可再改进更灵活;
<3>如果具体算法需要更多的参数(不只是一个”总价”),可以考虑使用实例类来参数进行聚合,再传入参数类。
使用”反射”解耦使用者必须”知道”具体策略类的编码时依赖。
八:升级版-使用反射
<1>动态加载一个程序集(exe,dll):
System.Reflection.Assembly.LoadFile(DLLfilename)
<2>获得一个程序集里的所有类型:
Assembly的实例.GetTypes()
<3>判断一个Type是否继承自指定的类:
Type的实例.IsSubclassOf(Type)
<4>获得一个Type的全名(包含所在命名空间):
Type的实例.FullName
<5>根据一个Type的全名,创建它的实例:
Assembly的实例.CreateInstance(Type的全名)
九:反射实现
StrategyDll.dll
using TestMain;
namespace StrategyDll
{
public class Gift : Strategy
{
public override void Algorithm(ref double currentTotal)
{
Console.WriteLine("送一个玩具!");
}
}
public class Discount : Strategy
{
public override void Algorithm(ref double currentTotal)
{
currentTotal *= 0.8;
Console.WriteLine("打八折!");
}
}
public class Reduce : Strategy
{
public override void Algorithm(ref double currentTotal)
{
if (currentTotal >= 300)
{
currentTotal -= 100;
Console.WriteLine("抵扣100元!");
}
else
{
Console.WriteLine("不够抵扣!");
}
}
}
}
TestMain.dll
using System.Text;
namespace TestMain
{
public abstract class Strategy
{
public abstract void Algorithm(ref double currentTotal);
}
public class Order
{
private double total;
public Order(double total)
{
this.total = total;
}
private List<Strategy> strategyList = new List<Strategy>();
public void AddStrategy(Strategy strategy)
{
this.strategyList.Add(strategy);
}
public string UsePromote()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this.strategyList)
{
sb.Append(this.UsePromote(item));
}
return sb.ToString();
}
public string UsePromote(Strategy strategy)
{
strategy.Algorithm(ref this.total);
return string.Format("最终价格:{0}\r\n", this.total);
}
}
}
StrategyWinform
namespace StrategyWinform
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
this.listBox1.Items.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
this.openFileDialog1.InitialDirectory = @"D:\Desktop\Test_C#\Test\StrategyDll\bin\Debug\net6.0\";
//Application.StartupPath;
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(this.openFileDialog1.FileName);
foreach (var item in assembly.GetTypes())
{
if (item.IsSubclassOf(typeof(TestMain.Strategy)))
{
object instanceOfStrategy = assembly.CreateInstance(item.FullName);
this.listBox1.Items.Add(instanceOfStrategy);
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
TestMain.Order order = new TestMain.Order(double.Parse(this.textBox1.Text));
foreach (var item in this.listBox1.SelectedItems)
{
order.AddStrategy(item as TestMain.Strategy);
}
var reuslt = order.UsePromote();
MessageBox.Show(reuslt);
}
}
}
十:总结
<1>Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。所谓封装算法,支持算法的变化。
<2>Strategy模式提供了用条件判断语句以外的另一种选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。
<3>与State类似,如果Strategy对象没有实例变量,那么各个上下文可以共享同一个Strategy对象,从而节省对象开销。
<4>结合反射技术,能达到最好的解耦效果。