c# - A static factory method on a generic or a non-generic class? -


i have generic class, let's call myclass<t>, need have factory method abstract constructor details away client code.

which of 2 options correct? (example instantiation code included)

  1. static non-generic factory method on original generic myclass<t>:

    myclass<sometype> instance = myclass<sometype>.createnew(); 
  2. static generic factory method on dedicated, non-generic static myclass implementation:

    myclass<sometype> instance = myclass.createnew<sometype>(); 

on first sight, looks proper answer question #1. because class myclass<t> , hence factory should t-specific. there more simple answer.

before proceeding, add third possibility: non-static factory class. object relies on factory have public property through receives factory object. getter of property instantiate default factory if no other instance has been assigned. allows dependency injection later, , helps write unit tests rely on own fake factory. solution (ignore generics moment):

public class isomefactory { ... }  public class defaultsomefactory: isomefactory { ... }  public class clientclass {     public isomefactory factoryofsome  // right place dependency injection     {                 {             if (_fact == null)                 _fact = new defaultfactory();             return _fact;         }         set { _fact = value; }     }     private isomefactory _fact; } 

now said, class goes generic parameter myclass<t> , factory should go generic parameter well: factory<t>. solution better generic method on general factory, because creating instance may t-specific. solution generic factory allows this:

public class specialsomefactory: defaultsomefactory<string> { ... } 

in way, can override behavior of existing factory class , have alternative way generate instances specialized strings. important because dealing strings different dealing primitive types int or double. having opportunity specialize factory may beneficial. see why might bad idea have static factory - statics cannot extended.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -