Search code examples
design-patternsclientadapter

Adapter Design Pattern: Expose private adaptee instance of the Adapter class Except for the Client code?


Is there any way I could have private adaptee instance inside the Adapter class exposed when I need it except for the client code?

To elaborate, there are certain cases where I would want to expose the adaptee instance from the Adaptor for the public, but I do Not want to do it with the client code. Therefore would it be appropriate to write a method within the Adapter class like this one:

public Adaptee ExposeAdaptee(){
    return _adapteeInstance;
}

enter image description here


Solution

  • This is called exposing a delegate. Though this is valid is some cases (beyond the scope of this answer), this is usually ill-advised because it violates the Law of Demeter and hence encapsulation. I wouldn't recommend it. The core idea behind any abstraction is hiding details; Adapter pattern is no different. In this case, we hide the delegate's interface behind one that the client expects. Exposing the delegate to the client would allow bypassing this abstraction, giving it multiple conflicting responsibilities -- not a good design decision.

    If the client needs the delegate, as well as the adapter, that shouldn't be a problem, because the client passes the delegate instance to the adapter's constructor anyway. Now, if you're saying other clients need access to the same delegate instance, then that's a different question altogether and you can use other patterns/solutions (Singleton or hoisting the instance into a common dependency).

    Anyways, I hope this helps!