Java: using polymorphism to avoid if-statements?

前端 未结 9 721
执念已碎
执念已碎 2020-12-29 08:30

I\'m attempting to write a java program that initializes certain layouts based on what the user selects. What I want to do is try to avoid writing a bunch of if-statements s

9条回答
  •  鱼传尺愫
    2020-12-29 09:10

    I think using if-statements for initialization is fine. You're trying to avoid the repeated use of if-statements to "select" behavior throughout the program. Using if-statements once for initialization is fine.

    To be sure, there are certainly ways to avoid even those initializer if-statements, but you have to decide what level of complexity and possible loss of readability is appropriate for your app.

    For example, here are some approaches to this problem from simple to more complex:

    • use those initializer if-statements
      • uses hard-coded references to implementing classes directly in the program logic (harder to find)
    • initialize some data structure (e.g. Map) with the possible implementing classes
      • still hard-coded references to implementing classes
      • generally easier to add more implementing classes
      • code is a little more complicated and abstract to understand and debug
    • use dynamic registration
      • no hard-coded references to the implementing classes in the app
      • more setup is required
      • code is harder to understand without knowing how the registration is setup to work

    A good example of the last method (dynamic registration) is to look at how JDBC works. JDBC drivers are registered in the app using Class.forName() and then a specific JDBC driver is selected using a JDBC URL. Here's a typical workflow:

    1. Potential target JDBC drivers are added classpath.

    2. The app is configured with a list of these drivers, e.g. by listing the JDBC drivers in a property file.

    3. The app initializes by calling Class.forName() on each driver in the list. Each driver knows to register itself with the DriverManager when it gets loaded by Class.forName()

    4. The app is determines what target database resource to use and resolving that to a JDBC URL, e.g. in a configuration dialog or user prompt.

    5. The app asks the DriverManager for a connection based on the target JDBC URL. The DriverManager polls each registered driver to see if it can handle the target JDBC URL until the DriverManager finds one that works.

    This would be the opposite extreme to avoid those if-statements.

提交回复
热议问题