c# - What creational pattern I should use? -


my program have 2 classes; both derive same base class.

class : mybase {     internal a(initval initval) }  class b : mybase {     internal b(initval initval) } 

initval class injected through constructor. class internal usage. due internal constructor, user cannot create instance of class a , b directly. instead, created method creates these objects.

class initiator {     initval initval;      public t createobject<t>(objectinstance objectinstance) t : mybase     {         mybase mybase = null;         switch(objectinstance)         {             case objectinstance.a:                 mybase = new a(initval);                 break;             case objectinstance.b:                 mybase = new b(initval);                 break;         }         return (t)mybase;     }     ... } 

objectinstance enum in above code.

this works without problem sure have never seen such ugly code earlier.

please suggest creational pattern should use. want remove objectinstance enum without changing functionality. cleanup much.

i tried creational patterns mentioned on dotfactory. factory method , abstract factory not proper in case.

my code though ugly, simple read , understand. tried implementing patterns mentioned above increases code complexity. criteria while choosing answer.

i cannot change in code except initiator class. other classes not accessible me edit.

edit 1: why above code ugly in view

1) while calling createobject method, user have specify type of object twice.

a = initiator.createobject<a>(objectinstance.a); 

first t generic value , second enum value. want avoid this.

2) user has specify type of object twice, there chances of mistake.

a = initiator.createobject<a>(objectinstance.b); 

in above code, enum value , generic value different. not allowed , problem. code, cannot avoid this.

that why; looking pattern suits case without increasing complexity.

if remove necessity of enum somehow, code lot better. if can change signature of createobject following, lot better.

public t createobject<t>() t : mybase 

but, not sure how implement method create proper instances.

it doesn't me getting advantage trying make generic. needs know concrete type of returned value @ call site.

therefore why not keep things simple , this?

public class initiator {     initval initval;      public createa()     {         return new a(initval);     }      public b createb()     {         return new b(initval);     } } 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -