Java: using polymorphism to avoid if-statements?

前端 未结 9 720
执念已碎
执念已碎 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:14

    You should use a framework to avoid if's to create o define behavior.

    Spring lets us to manage and solve this issue. It uses a factory pattern and more design patterns. So using annotations or xml configuration file you can decide what classes create. PD: Of course, I'm 100% secure that spring uses if's. But it's proved and used in many strong and reliable apps.

    0 讨论(0)
  • 2020-12-29 09:15

    "..for future use if more layouts need to be added"

    I'd also suggest you look into the factory pattern. If you contain this conditional logic within a factory, it should help down the line with maintenance and readability.

    0 讨论(0)
  • Since java doesn't have first class functions, you can use interfaces to wrap around.

    LayoutHandler ~> Interface
    
    LayoutHandlerA, LayoutHandlerB, etc implements LayoutHandler
    
    Map<String, LayoutHandler> handlers = new HashMap<...>();
    
    LayoutHandler handler = handlers.get(userSelectedLayout);
    
    handler.handle();
    
    0 讨论(0)
提交回复
热议问题