再來我們進階提到 簡單工廠 這還滿常用到的
主要是建立個類別去負責分配要到哪個工廠做事情
我們可以在主邏輯分配 次要邏輯 要處理的事情
一方面可以增加可讀性 功能也不會雜亂的都寫在一起
public class Factory
{
static void Main(string[] args)
{
Console.WriteLine("選擇列印類型");
Console.WriteLine("0:Method1");
Console.WriteLine("1:Method2");
Console.WriteLine("2:Method3");
string type = Console.ReadLine();
typeenum item = (typeenum)Enum.Parse(typeof(typeenum), type, false);
var method = Factory.CreatePrint(item);
Console.Write(method.Print());
Console.Read();
}
public static IHandler CreatePrint(typeenum type) {
if (type == typeenum.type1)
{
return new Method1();
}
else if (type == typeenum.type2)
{
return new Method2();
}
else if (type == typeenum.type3)
{
return new Method3();
}
return new Method4(); ;
}
}
public class Method1 : IHandler
{
public string Print()
{
return "hellow word! type1";
}
}
public class Method2 : IHandler
{
public string Print()
{
return "hellow word! type2";
}
}
public class Method3 : IHandler
{
public string Print()
{
return "hellow word! type3";
}
}
public class Method4 : IHandler
{
public string Print()
{
return "hellow word! type4";
}
}
public interface IHandler
{
string Print();
}
public enum typeenum
{
type1,
type2,
type3,
}



沒有留言:
張貼留言