Is this Factory Method creation pattern?

前端 未结 20 813
再見小時候
再見小時候 2020-12-12 17:12

I have been using factory method creation pattern for awhile now. I was just recently told that this:

public static class ScheduleTypeFactory
{
    public st         


        
相关标签:
20条回答
  • 2020-12-12 18:02

    I think it is traditionally called the simple factory pattern to distinguish it from the 'real' Abstract Factory pattern. It might be that you are not adhering to some sort of internal naming practice. She really ought to explain herself though.

    0 讨论(0)
  • 2020-12-12 18:04

    That is the Factory pattern, but it's not necessarily the most maintainable variant. A more maintainable variant would maintain some sort of global map between ScheduleTypeEnum values and actual concrete subtypes of IScheduleItem -- that way, you could replace the switch statement with a lookup of the map.

    Why is it more maintainable? Because subclass authors can add pairs to the map at the site where they derive the class, rather than in the GetScheduleItem() factory function itself. Hence the latter never needs updating; it is constantly up-to-date.

    In C++ you can do this using a global std::map -- for each concrete subclass, the author of the subclass adds a dummy global variable which actually just registers the class (by adding to the map) in its constructor, which runs at program startup time. I'm certain that there's a convenient way to do the same thing in C#.

    (C++ guru Herb Sutter has an entertaining description here, but it's fairly C++-heavy.)

    0 讨论(0)
提交回复
热议问题