这是我通常看到的抽象工厂模式的方式:
public abstract class Factory
{
public abstract Product GetProduct();
}
public class ConcreteFactory1 : Factory
{
public override Product GetProduct() { return new Product1(); }
}
class ConcreteFactory2 : Factory
{
public override Product GetProduct() { return new Product2(); }
}
interface Product
{
void SomeMethod();
}
class Product1 : Product
{
public void SomeMethod() { Console.WriteLine("1"); }
}
class Product2 : Product
{
public void SomeMethod() { Console.WriteLine("2"); }
}
class Program
{
static void Main(string[] args)
{
Factory f = null;
Product p = null;
switch (args[0])
{
case "1":
f = new ConcreteFactory1();
p = f.GetProduct();
break;
case "2":
f = new ConcreteFactory2();
p = f.GetProduct();
break;
}
p.SomeMethod();
}
}
我通常这样写,这不是真正的模式:
interface Product
{
void SomeMethod();
}
class Product1 : Product
{
public void SomeMethod() { Console.WriteLine("1"); }
}
class Product2 : Product
{
public void SomeMethod() { Console.WriteLine("2"); }
}
public static class Factory
{
public static Product GetProduct(prodType)
{
Product p = null;
switch (prodType)
{
case "1":
p = new Product1();
break;
case "2":
p = new Product2();
break;
}
return p;
}
}
class Program
{
static void Main(string[] args)
{
Product p = Factory.GetProduct(args[0]);
p.SomeMethod();
}
}
我的问题是——混凝土工厂的优势是什么?我从来不明白这一点——它似乎只是增加了另一个不必要的层。第二个例子看起来更加简洁明了。