我一直在做一些閱讀戰略模式,並有一個問題。我已經在下面實現了一個非常基本的控制檯應用程序來解釋我在問什麼。沒有'switch'語句的策略模式?
我已經讀過,在執行策略模式時,'switch'語句是紅旗。不過,在這個例子中,我似乎無法擺脫switch語句。我錯過了什麼嗎?我能夠從鉛筆刪除邏輯,但我的主現在有一個switch語句。我明白我可以輕鬆創建一個新的TriangleDrawer類,而不必打開鉛筆類,這很好。但是,我需要打開Main以便它知道哪種類型的IDrawer要傳遞給鉛筆。如果我依靠用戶進行輸入,這只是需要做什麼?如果沒有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();
}
}
}
實施的解決方案(感謝所有誰回答!) 該解決方案讓我的地步,我需要做的唯一的事情用一個新的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();
}
}
}
可能導致開/關原理被違反的開關語句是壞的。策略模式有助於將switch語句從希望保持它關閉的地方分離出來,但是仍然需要處理選擇策略/實現的地方,無論是switch語句,if/else/if還是使用LINQ Where(這是我的最愛:-)順便說一下,策略模式也可以幫助您輕鬆地模擬策略實施,從而幫助單元測試。 – kimsk 2013-01-23 06:35:12