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 ap
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.
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'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.
The factory pattern is very useful to map a capacity into an apropriate handler.
namely in one of 2 cases:
Admittedly the need for actual use of the more painful implementation details described by the pattern were removed thanks to the way C# works, but my SQL DAL functionality passes around object factories (and SQL commands) to utility functions that use the factories in order to generate objects. If I was not using C#, I suppose I could instead have used an explicit factory class that generated the objects.