Design Pattern or Accepted Solutions for Avoiding Switching on Types

后端 未结 2 820
半阙折子戏
半阙折子戏 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-20 21:13
    1. Use a static collection of 'Converters' (or whatever) that all implement a common interface. Then you can iterate over that collection asking each if they handle the type. If they do, then ask them to do it. Each converter only knows about its type.
    2. Use the same static 'collection' of converters but hold them in a Dictionary keyed by type. Then request the converter by type from the dictionary and ask it to convert for you.
    0 讨论(0)
提交回复
热议问题