Take the following class hierarchy:
Client
FacebookClient
PinterestClient
TwitterClient
Each client must define a value for an enum property named ClientType
(string property Url
in the original version of this question; hence the accepted answer). ClientFactory
should then be able to instantiate by client type.
ClientFactory.Create(ClientType.Facebook);
ClientType
could be a static property for each subtype, and then subtypes could be selected by its value in the factory:
// Create array of possible client subtypes
Type[] clients = new[] { typeof(FacebookClient), typeof(PinterestClient), typeof(TwitterClient) };
// Select subtype with URL that matches one passed to factory
Type client = clients.SingleOrDefault(c => clientType == (Client)c.GetProperty("ClientType").GetValue(null));
return (Client)Activator.CreateInstance(client, parameters);
However, since static members can't be abstract, I'm not sure of a way to ensure that ClientType
is set, and there are dozens of subtypes.
Is there a way to force ClientType
to be set? Would another way of doing this (e.g., a switch
statement) be a better option?
Url
is already defined/has to be used elsewhere, it would be better to select on it versus redefining it in aswitch
statement. I haven't worked a whole lot with factories, so I'm sure I'm missing things here. I appreciate the help.factory.CreateFacebookClient()
etc... ?ClientType
is an enum that users can choose multiple values from on the application's front end. These values are then passed to the factory, which creates the appropriate instances. The caller can then loop through them and call implementations of abstract methods defined in the baseClient
class that apply to all subtypes, likePostMessage
.