JSp*_*ang 49 c# design-patterns dependency-injection coding-style strategy-pattern
我一直在阅读战略模式,并有一个问题.我在下面实现了一个非常基本的控制台应用程序来解释我在问什么.
I have read that having 'switch' statements is a red flag when implementing the strategy pattern. However, I can't seem to get away from having a switch statement in this example. Am I missing something? I was able to remove the logic from the Pencil, but my Main has a switch statement in it now. I understand that I could easily create a new TriangleDrawer class, and wouldn't have to open the Pencil class, which is good. However, I would need to open Main so that it would know which type of IDrawer to pass to the Pencil.如果我依赖用户输入,这是否需要做什么?如果没有switch语句就有办法做到这一点,我很乐意看到它!
class Program
{
public class Pencil
{
private IDraw drawer;
public Pencil(IDraw iDrawer)
{
drawer = iDrawer;
}
public void Draw()
{
drawer.Draw();
}
}
public interface IDraw
{
void Draw();
}
public class CircleDrawer : IDraw
{
public void Draw()
{
Console.Write("()\n");
}
}
public class SquareDrawer : IDraw
{
public void Draw()
{
Console.WriteLine("[]\n");
}
}
static void Main(string[] args)
{
Console.WriteLine("What would you like to draw? 1:Circle or 2:Sqaure");
int input;
if (int.TryParse(Console.ReadLine(), out input))
{
Pencil pencil = null;
switch (input)
{
case 1:
pencil = new Pencil(new CircleDrawer());
break;
case 2:
pencil = new Pencil(new SquareDrawer());
break;
default:
return;
}
pencil.Draw();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
实现的解决方案如下所示(感谢所有响应的人!)这个解决方案让我到了使用新的IDraw对象我唯一需要做的就是创建它.
public class Pencil
{
private IDraw drawer;
public Pencil(IDraw iDrawer)
{
drawer = iDrawer;
}
public void Draw()
{
drawer.Draw();
}
}
public interface IDraw
{
int ID { get; }
void Draw();
}
public class CircleDrawer : IDraw
{
public void Draw()
{
Console.Write("()\n");
}
public int ID
{
get { return 1; }
}
}
public class SquareDrawer : IDraw
{
public void Draw()
{
Console.WriteLine("[]\n");
}
public int ID
{
get { return 2; }
}
}
public static class DrawingBuilderFactor
{
private static List<IDraw> drawers = new List<IDraw>();
public static IDraw GetDrawer(int drawerId)
{
if (drawers.Count == 0)
{
drawers = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => typeof(IDraw).IsAssignableFrom(type) && type.IsClass)
.Select(type => Activator.CreateInstance(type))
.Cast<IDraw>()
.ToList();
}
return drawers.Where(drawer => drawer.ID == drawerId).FirstOrDefault();
}
}
static void Main(string[] args)
{
int input = 1;
while (input != 0)
{
Console.WriteLine("What would you like to draw? 1:Circle or 2:Sqaure");
if (int.TryParse(Console.ReadLine(), out input))
{
Pencil pencil = null;
IDraw drawer = DrawingBuilderFactor.GetDrawer(input);
pencil = new Pencil(drawer);
pencil.Draw();
}
}
}
Run Code Online (Sandbox Code Playgroud)
bra*_*ter 53
策略不是一种神奇的反交换解决方案.它所做的是为您的代码提供模块化,以便在维护噩梦中混合使用大型交换机和业务逻辑
例如 - 如果您在main方法中接受了切换并创建了一个接受命令行参数的类并返回了IDraw的实例(即它封装了该开关),那么您的main将再次清理,并且您的开关位于其唯一目的的类中是实施那个选择.
Muh*_*han 17
以下是仅为了避免if/ switch陈述而对您的问题进行过度设计的解决方案.
CircleFactory: IDrawFactory
{
string Key { get; }
IDraw Create();
}
TriangleFactory: IDrawFactory
{
string Key { get; }
IDraw Create();
}
DrawFactory
{
List<IDrawFactory> Factories { get; }
IDraw Create(string key)
{
var factory = Factories.FirstOrDefault(f=>f.Key.Equals(key));
if (factory == null)
throw new ArgumentException();
return factory.Create();
}
}
void Main()
{
DrawFactory factory = new DrawFactory();
factory.Create("circle");
}
Run Code Online (Sandbox Code Playgroud)
Guy*_*uck 14
我不认为您的演示应用程序中的切换实际上是策略模式本身的一部分,它只是用于练习您定义的两种不同策略.
"开关是红旗"警告是指在策略内部有开关; 例如,如果您定义了一个策略"GenericDrawer",并且让它确定用户是否想要在内部使用针对参数值的开关的SquareDrawer或CircleDrawer,那么您将无法获得策略模式的好处.
Muh*_*han 14
你也可以if借助字典来摆脱它
Dictionary<string, Func<IDraw> factory> drawFactories = new Dictionary<string, Func<IDraw> factory>() { {"circle", f=> new CircleDraw()}, {"square", f=> new SquareDraw()}}();
Func<IDraw> factory;
drawFactories.TryGetValue("circle", out factory);
IDraw draw = factory();
Run Code Online (Sandbox Code Playgroud)
小智 5
有点晚了,但对于仍然有兴趣完全删除条件语句的任何人。
class Program
{
Lazy<Dictionary<Enum, Func<IStrategy>>> dictionary = new Lazy<Dictionary<Enum, Func<IStrategy>>>(
() =>
new Dictionary<Enum, Func<IStrategy>>()
{
{ Enum.StrategyA, () => { return new StrategyA(); } },
{ Enum.StrategyB, () => { return new StrategyB(); } }
}
);
IStrategy _strategy;
IStrategy Client(Enum enu)
{
Func<IStrategy> _func
if (dictionary.Value.TryGetValue(enu, out _func ))
{
_strategy = _func.Invoke();
}
return _strategy ?? default(IStrategy);
}
static void Main(string[] args)
{
Program p = new Program();
var x = p.Client(Enum.StrategyB);
x.Create();
}
}
public enum Enum : int
{
StrategyA = 1,
StrategyB = 2
}
public interface IStrategy
{
void Create();
}
public class StrategyA : IStrategy
{
public void Create()
{
Console.WriteLine("A");
}
}
public class StrategyB : IStrategy
{
public void Create()
{
Console.WriteLine("B");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22920 次 |
| 最近记录: |