public ConcreteFactory(IFactory f1, IFactory f2)
{
factory1 = f1;
factory2 = f2;
}
public T1 Create(TypeToken token)
{
return factory1.Create();
}
public T2 Create(TypeToken token)
{
return factory2.Create();
}
}
public static class ConcretFactory
{
public static ConcreteFactory NewFactory (IFactory f1, IFactory f2)
{
return new ConcreteFactory (f1, f2);
}
}
注意,我又声明了一个没有类型参数的ConcretFactory类,用一个静态方法来生成泛型ConcretFactory的实例,这是因为使用泛型方法可以推测类型参数,使得我们可以不必输入尖括号或Of语句,而泛型类则没有这个功能。现在大功告成!我们用一个例子来演示这个泛型抽象工厂的工作情况。现在假设我们需要一个生产PC的抽象工厂,需要生产两种抽象产品:处理器和内存。处理器和内存的抽象和具体实现如下:
Processor 和 Ram
public abstract class Processor
{
public abstract string Model { get; }
}
public abstract class Ram
{
public abstract int Frequency { get;}
}
public class PentiumProcessor : Processor
{
public override string Model
{
get { return "Pentium Extreme Edition 955"; }
}
}
public class AthlonProcessor : Processor
{
public override string Model
{
get { return "Athlon 64 X2 FX-60"; }
}
}
public class DDRRam : Ram
{
public override int Frequency
{
get { return 400; }
}
}
public class DDR2Ram : Ram
{
public override int Frequency
{
get { return 533; }
}
}
下面的代码演示了如何随心所欲生成想要的抽象工厂接口以及快速从现有单一产品工厂组合成特定的具体工厂实现。
class Program
{
static IAbstractFactory ComputerFactory(string type)
{
if (type == "Intel")
{
return ConcretFactory.NewFactory( new OpNewFactory (),
new OpNewFactory ());
}
else if (type == "AMD")
{
return ConcretFactory.NewFactory( new OpNewFactory (),
new OpNewFactory ());
}
//unknown type
return null;
}
static void Main(string args)
{
//Yield a computer of Intel
IAbstractFactory factory1 = ComputerFactory("Intel");
Ram ram1 = factory1.Create(TypeToken .Instance);
Processor cup1 = factory1.Create(TypeToken .Instance);
Console.WriteLine("An Intel Computer");
Console.WriteLine("CPU Model: {0}", cup1.Model);
Console.WriteLine("Memory Frequency: {0} MHz", ram1.Frequency);
Console.WriteLine();
//Yield a computer of AMD
IAbstractFactory factory2 = ComputerFactory("AMD");
Ram ram2 = factory2.Create(TypeToken .Instance);
Processor cup2 = factory2.Create(TypeToken .Instance);
Console.WriteLine("An AMD Computer");
Console.WriteLine("CPU Model: {0}", cup2.Model);
Console.WriteLine("Memory Frequency: {0} MHz", ram2.Frequency);
}
}
总结:
我们用泛型技术成功地增强了原本重用性较低的抽象工厂,演示了泛型在提高抽象性和代码重用方面卓越的价值。