我想在C++中实现策略模式,但我有疑问。 Alwyas的策略模式示例比遵循代码(在C#中)。我想修改客户端,即MainClass,这样选择具体的策略将是动态的。 例如,通过main方法的args []参数传递策略名称。我将如何在不修改这种模式的属性的情况下实现这一点?策略模式C++
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 come the actual imp
}
}
// BubbleSort
public class CBubbleSort : ISort
{
void Sort(List<string> list)
{
// The actual imp of the sort
}
}
public class Context
{
private ISort sorter;
public Context(ISort sorter)
{
// We pass 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");
Contexto cn = new Contexto(new CQuickSorter());
cn.Sorter.Sort(myList);
cn = new Contexto(new CBubbleSort());
cn.Sorter.Sort(myList);
}
}
}
这应该是哪种语言?至少1个拼写错误和几个语法错误..看起来更像C#? – 2013-02-25 02:08:14
作为@KarthikT答案,你不能直接从C++中的字符串做到这一点,他的答案是一种方法。 “依赖注入”可能是一个很好的搜索术语,用于以各种方式查看用于执行此类事件的框架(包括一些动态的)。 – 2013-02-25 02:10:52