33

As far as understand, the adapter pattern is creating a wrapper object for our real object of interest, simply one more level of indirection, which provides flexibility. the flexibility is in that, if the real object's interface is changed, then we change the wrapper interface pointing at the real object, leaving the client-side exposed interface unchanged.

The proxy pattern is the same, with the difference that every proxy wrapper provides only a coherent subset of the real object's functionality. Why would this be useful, when we strive to make "one class for one purpose" is beyond me.

Have I gotten this correctly?

55

Not entirely.

The primary purpose of the adapter pattern is to change the interface of class/library A to the expectations of client B. The typical implementation is a wrapper class or set of classes. The purpose is not to facilitate future interface changes, but current interface incompatibilities.

The proxy pattern also uses wrapper classes, but for a different purpose. The purpose of the proxy pattern is to create a stand-in for a real resource. Reasons for using a proxy can be

  • The real resource resides on a remote computer (the proxy facilitates the interaction with the remote resource)
  • The real resource is expensive to create (the proxy ensures the cost is not incurred unless/until really needed)

The most important thing is that a proxy provides a drop-in replacement for the real resource it is a stand-in for, so it must provide the same interface.

  • First of all, thanks for the great answer. Does a proxy implement all interfaces that the current client need, or does it implement all interfaces that the actual resource provide? – Vorac Jun 13 '13 at 11:02
  • 1
    @Vorac: That depends on the complexity of the interface and your design philosophy. Both are possible, but if the interface is large/complex or you strongly believe in YAGNI, then it makes more sense to implement only what you need. – Bart van Ingen Schenau Jun 13 '13 at 11:55
  • So, given that the Adapter pattern uses wrapper classes, is the Adapter pattern a proxy pattern? – moonman239 Jul 6 '18 at 18:22
  • @moonman239: No, because the intention for using a wrapper class is different. Just because two patterns look similar in a class diagram does not mean that they are related or implement each other. A major factor for patterns to be different is their intent. – Bart van Ingen Schenau Jul 6 '18 at 18:59
4

I like this explanation:

The Proxy changes the behavior of the Service, but preserves its interface.

The Adapter changes the interface of the Service, but preserves it behavior.

source: https://www.netobjectives.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.