UPDATE: this is a duplicate of
Is the StaticFactory in codecampserver a well known pattern?
UPDATE: this is a duplicate of Is the StaticFactory in codecampserver a well known
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Edit: Please note that this answer was given before the question was completely changed over in an edit. Because of that, it now refers to things that were only present in the question as originally stated. I beg your pardon for all the “dangling pointers”. 🙂
Short answer:
With the code you’ve posted, I don’t see an alternative to casting to
IFoo<T>. If you don’t, the compiler will give a warning (on my machine, at least).More elaborate answer:
Does your code actually have to be that way? More specifically, do you need the cast in question in the first place?
I assume you are going to call your factory method more or less like this:
You have to provide the template parameter (
stringin this case) explicitly because it cannot be derived from any method argument (in this case because there aren’t actually any at all). Obviously, the factory method will return anIFoo<string>.Now, since you have to explicitly specify the type at run-time, you could just as well write:
and therefore have a factory method inside
StringFoo, like this, that unconditionally does the obvious:By applying this pattern to other
IFoo<T>implementations too, this will save you theifchain orswitchblock insideFooFactory.CreateFoo<T>, make your code easier, and get rid of the necessity to cast (which you are concerned about).Don’t get me wrong, I’m aware that factory methods supporting more than one object type are useful in some cases; but it seems in your case it causes more trouble than it’s worth.
P.S.: You might find one aspect of some IoC containers interesting. They usually need to be configured, and this encompasses a process where you register concrete types (i.e. implementation classes) for abstract interfaces; for example (here using Autofac):
Then later, you can request an object instance of an abstract type:
The
Resolvemethod is the interesting part. You provide it with an abstract type, and using the registered types, it will return a concrete object of typeStringFoo. Look into it, if it doesn’t sound like overkill to you! 🙂