Search code examples
design-patternsadapter

How Adapter Pattern Resolve Dependencies?


I have a question with the Adapter Pattern. I am implementing this pattern because I have a third-party library and don’t want to depend upon it.

However, I dont’t get why creating the IAdapter and the Adapter in the same proyect will remove a dependency.

Because if the third-party library changes, the package need to be recompiled, so also any class that uses the IAdapter also needs to be recompiled.

Does the IAdapter and the Adapter must be in different packages?


Solution

  • Measure of whether 2 components/classes are decoupled or not isn't merely based on the need to recompile the package. There are multiple dimensions to it.

    1. Can you replace third-party library from the client app without causing any code change in client of IAdapter?
    2. Can you replace third-party library without need of rebuilding client of IAdapter?
    3. In some cases, can you replace third-party library at runtime without full application server restart?

    Depending on your needs, here is how you can achieve above goals.

    1. You can have IAdapter implemented by ThirdParty1Adapter. If you wish to replace it, you can implement ThirdParty2Adapter that fulfills all contracts of IAdapter. Your IAdapter clients will be unaffected.
    2. You may bundle implementation class of IAdapter in a dedicated jar. Client application would expect one of the implementation of IAdapter to be provided by DI container or application server. There are options here, but just being technology agnostic here.
    3. You need a runtime that allows you to add jars dynamically and replace dependencies in existing classes loaded by runtime. You can use class pattern common in OSGi that suggests creating dedicated API bundle, Provider bundle & consumer bundles. You can add/replace provider bundles in your OSGi runtime that can be picked up and injected in already running classes.