它是如何运作的,它有什么用途,以及什么时候应该使用它?
它是如何运作的,它有什么用途,以及什么时候应该使用它?
让我们通俗易懂地解释策略模式:
你有一个类 Car()
,带有方法run()
,在伪代码中可以这样使用:
mycar = new Car()
mycar.run()
现在,您可能想在程序执行时动态更改run()
的行为。例如,您可能希望模拟电机故障或在视频游戏中使用“增强”按钮。
有几种方法可以进行此仿真:使用条件语句和标志变量是一种方法。另一种方法是策略模式:它将run()
方法的行为委托给另一个类:
Class Car()
{
this.motor = new Motor(this)
// passing "this" is important for the motor so it knows what it is running
method run()
{
this.motor.run()
}
method changeMotor(motor)
{
this.motor = motor
}
}
如果你想改变汽车的行为,只需更换电机即可。(在程序中比现实生活中容易多了,对吧?;-))
如果你有很多复杂状态,这就非常有用:你可以更轻松地改变和维护它们。
策略模式用于解决可能需要使用不同的策略来实现或解决,并且对于这些情况已经定义了明确定义的接口。每种策略本身都是完全有效的,其中某些策略在允许应用程序在运行时在它们之间切换的某些情况下更可取。
namespace StrategyPatterns
{
// Interface definition for a Sort algorithm
public interface ISort
{
void Sort(List<string> list)
}
// QuickSort implementation
public class CQuickSorter : ISort
{
void Sort(List<string> list)
{
// Here will be the actual implementation
}
}
// BubbleSort implementation
public class CBubbleSort : ISort
{
void Sort(List<string> list)
{
// The actual implementation of the sort
}
}
// MergeSort implementation
public class CMergeSort : ISort
{
void Sort(List<string> list)
{
// Again the real implementation comes here
}
}
public class Context
{
private ISort sorter;
public Context(ISort sorter)
{
// We pass to the context the strategy to use
this.sorter = sorter;
}
public ISort Sorter
{
get{return sorter;)
}
}
public class MainClass
{
static void Main()
{
List<string> myList = new List<string>();
myList.Add("Hello world");
myList.Add("Another item");
myList.Add("Item item");
Context cn = new Context(new CQuickSorter());
// Sort using the QuickSort strategy
cn.Sorter.Sort(myList);
myList.Add("This one goes for the mergesort");
cn = new Context(new CMergeSort());
// Sort using the merge sort strategy
cn.Sorter.Sort(myList);
}
}
}
Context
类中拥有 get for ISort
的作用是什么?不确定在什么情况下会有用? - BillaSorter
是私有的,我们可以使用cn.Sorter
吗? - Jason Law使用该模式使得添加或删除特定行为更加容易,无需重新编写和重测整个应用程序或其部分。
适用场景:
直接摘自策略模式维基百科文章:
策略模式适用于需要动态交换应用程序中使用的算法的情况。 策略模式旨在提供一种定义算法族的方法,将每个算法封装为一个对象,并使它们可以互换。 策略模式使得算法可以独立于使用它们的客户端而变化。