Design Pattern or Accepted Solutions for Avoiding Switching on Types

后端 未结 2 843
半阙折子戏
半阙折子戏 2020-12-20 20:35

I\'m trying to find a good, clean design pattern or commonly accepted implementation to deal with an enumeration of types where the individual type is known only at runtime.

2条回答
  •  猫巷女王i
    2020-12-20 20:59

    Use the Strategy design pattern:

    Define separate converter objects (with a common interface) that encapsulate the different converting algorithms. Clients delegate the converting to the proper converter object at run-time.

    This greatly reduces implementation dependencies. Client code is independent of how the converting is implemented.

    I agree with @David Osborne's answer. And even if you implement a single converter object with a switch statement, this implementation is encapsulated and hidden from clients.

提交回复
热议问题