Instantiate proper class based on some input

Posted by Adam Backstrom on Programmers See other posts from Programmers or by Adam Backstrom
Published on 2012-06-22T13:24:26Z Indexed on 2012/06/22 15:24 UTC
Read the original article Hit count: 265

Filed under:
|

I'm attempting to understand how "switch as a code smell" applies when the proper code path is determined by some observable piece of data.

My Webapp object sets an internal "host" object based on the hostname of the current request. Each Host subclass corresponds to one possible hostname and application configuration: WwwHost, ApiHost, etc. What is an OOP way for a host subclass to accept responsibility for a specific hostname, and for Webapp to get an instance of the appropriate subclass?

Currently, the hostname check and Host instantiation exists within the Webapp object. I could move the test into a static method within the Host subclasses, but I would still need to explicitly list those subclasses in Webapp unless I restructure further. It seems like any solution will require new subclasses to be added to some centralized list.

© Programmers or respective owner

Related posts about php

Related posts about object-oriented