我有一個簡單的抽象工廠實現:抽象工廠使用Unity
public abstract class ICarFactory{
public abstract ISportsCar CreateSportCar();
public abstract IFamilyCar CreateFamilyCar();
}
public abstract class ISportsCar {
public abstract void Accelerate();
}
public abstract class IFamilyCar {
public abstract void Accelarete();
}
public class BMWFactory : ICarFactory {
public override ISportsCar CreateSportCar() {
return new BMWi7();
}
public override IFamilyCar CreateFamilyCar() {
return new BMWM5();
}
}
public class WolksvagenFactory : ICarFactory {
public override ISportsCar CreateSportCar() {
return new WVGolfR();
}
public override IFamilyCar CreateFamilyCar() {
return new WVGolf();
}
}
public class BMWi7 : ISportsCar {
public override void Accelerate() {
Console.WriteLine(this.ToString() + "accelerated.");
}
}
public class BMWM5 : IFamilyCar {
public override void Accelarete() {
Console.WriteLine(this.ToString() + "accelerated.");
}
}
public class WVGolfR : ISportsCar {
public override void Accelerate() {
Console.WriteLine(this.ToString() + "accelerated.");
}
}
public class WVGolf : IFamilyCar {
public override void Accelarete() {
Console.WriteLine(this.ToString() + "accelerated.");
}
}
客戶端代碼是這樣的:
class Program
{
static void Main(string[] args)
{
ISportsCar sportsCar = GetFactory().CreateSportCar();
sportsCar.Accelerate();
}
static ICarFactory GetFactory()
{
string userLocation;
userLocation = "Hamburg"; //Get user location from user settings
if (userLocation == "Hamburg")
{
return new BMWFactory();
}
else
{
return new WolksvagenFactory();
}
}
}
是否有可能實現通過完成任務「GetFactory()」方法通過使用Microsoft.Practices.Unity?
我已經通過搜索這個問題了很多時間。但我找不到有用的東西。
謝謝,這真棒。 – fkucuk 2014-11-05 14:44:46