I'm pretty new to Design Patterns.I just came across Factory Design Pattern. I understood that it delegates the instantiation to subclasses. But I didn't get the actual application of the pattern. In which scenarios can this pattern be used to good effect. I've heard of pattern abuse and would not like to indulge in that. Can anyone mention a real world example where it is commonly used.
I've used it for plugins to applications... this way you can have your main application call the class factory to instantiate the specific plugin implementing some interface that you've developed to in your main app. This way, you can code the main portion of your application without ever needing to know what is going to be plugged in.
namely in one of 2 cases:
Suppose you have a queue that holds objects of type task
.
Now, you can subclass task
for various reasons. If you are loading your tasks from some source like a database, you could use a factory to determine what task type to load.
For example:
private IEnumerable<Task> GetTasks(DataTable Table){
Task NewTask;
foreach(DataRow Row in Table){
switch(tasktype){
case tasktypes.TaskTypeA:
NewTask = NewTaskA(...);
break;
case TaskTypes.TaskTypeB:
NewTask = NewTaskB(...);
break;
...
}
yield return NewTask;
}
}
Later you could then call virtual methods on the tasks in your queue, like "consume" or "process", for example.
The advantage to the factory approach (in this case) is that you only have to switch on task type once (when the task is created), and let polymorphism handle most everything else.
I just used it in a scheduling application, where the tasks to be scheduled are in separate assemblies, and the scheduler does not know anything about the tasks... It gets the name of the assembly the task is defined in from an external source, and then loads the assembly dynamically, instantiates a class in that assembly using a well-defined interface. A factory method in the scheduler, that takes the assembly name as an input parameter, returns an instance of the class in the loaded assembly...
.. but there are so many uses, and ways to use.. this pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With