What are the practical uses of Factory Method Pattern?

前端 未结 6 942
闹比i
闹比i 2021-01-11 09:51

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

6条回答
  •  没有蜡笔的小新
    2021-01-11 10:17

    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 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.

提交回复
热议问题