2014-02-07 50 views
1

我試圖做花哨的東西是這樣的:接口採用通用的工廠

我有以下代碼:

public interface IMyInterface 
    { 
     void Method1(); 
    } 

    public interface IClassFactory 
    { 
     object GetObject(); 
    } 

    public interface IGenericClassFactory<T> where T: IMyInterface 
    { 
     T GetObject(); 
    } 

public class MyClass : IMyInterface 
    { 
     public void Method1() 
     { 
      Console.WriteLine("Medota 1"); 
     } 

    } 

    public class MyFactory : IClassFactory 
    { 
     public object GetObject() 
     { 
      return new MyClass(); 
     } 
    } 

    public class MyGenericFactory<T> : IGenericClassFactory<T> where T : IMyInterface, new() 
    { 
     public T GetObject() 
     { 
      // T t = new T(); 
      //return t; 
      //var ctor = typeof(T).GetConstructor(new Type[0]);//1] { typeof(int) }); 
      //if (ctor != null) 
      //{ 
      // return (T)ctor.Invoke(new object[0]); // new object[1] { 5}); 
      // //return Activator.CreateInstance<T>(); //to samo co wyzej tylko nie jest bezpieczne 
      //} 
      //throw new InvalidOperationException("T nie posiada domyślnego konstruktora"); 
      // return Activator.CreateInstance<T>(); //bez parametrów 
      // return (T)Activator.CreateInstance(typeof(T), 5, "EOG", new object()); // z parametrami 
      return new T(); 

     } 
    } 




static void Main(string[] args) 
     { 
      IClassFactory factory; 
      factory = new MyFactory(); 

      IGenericClassFactory<IMyInterface> genFactory; 
      genFactory = new MyGenericFactory<MyClass>(); //Do not compile! 

      MyClass obj = genFactory.GetObject() as MyClass; 

      obj.Method1(); 
      Console.ReadKey(); 
     } 

我能做到這一點,如:

IGenericClassFactory<IMyInterface> genFactory; 
      genFactory = new MyGenericFactory<MyClass>(); 

//所以我可以選擇創建對象

但我認爲這是毫無意義的,因爲我想擁有多於一個對象的工廠。 你能幫助我嗎?

提前THX

+1

這種模式是無用的。工廠沒有真正的目的。工廠應該隱藏實現該接口的類,以便可以用另一個替代它。在你的情況下,工廠方法*接收*實現類作爲參數,這使工廠無用。 – Alex

回答

2

你不應該讓你的工廠類通用,但該方法GetObject應該是通用的:

public T GetObject<T>() where T: IMyInterface, new() 

然後:

static void Main(string[] args) 
{ 
     var factory = new MyFactory(); 
     var obj = factory.GetObject<MyClass>(); 

     obj.Method1(); 
     Console.ReadKey(); 
} 

所以,這一切的一切,你應該得到擺脫您的通用代碼,並簡單地修改您的MyFactory類

public class MyFactory : IClassFactory 
{ 
    public T GetObject<T>() 
    { 
     //TODO - get object of T type and return it 
     return new T(); 
    } 
} 

順便說一句 - 我不確定這個通用實現的目的是什麼?從使用工廠模式的角度來看它有什麼意義嗎?

+0

我的想法是做工廠,生成繼承IMyInterface的對象,但現在你告訴我,它是錯誤的。 –