Chapter 9. Factory Pattern
The largest switch/case statement I've ever seen in an object-oriented program had more than 20 conditions. Upon execution, this block of code was executed one time for each condition. Each condition was responsible for creating a new object. This object was used to communicate with external consumers of the application's API. After performing some routine troubleshooting on one of the classes, I investigated the interface it implemented. To my surprise, each of the classes referenced in that switch/case statement implemented the same interface! The next time a new condition was being added to that switch/case, I suggested we move to the Factory pattern. As indicated earlier, the names of Design Patterns are very important. They not only provide uniformity to referencing each Design Pattern, but they also key into what the pattern exactly does. In the case of the code I was looking at, the Factory Design Pattern was a perfect match for this assembly line of class creation.
Name: FactoryThe Factory Design Pattern provides a simple interface to acquire a new instance of an object, while sheltering the calling code from the steps to determine which base class is actually instantiated. |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access