What is the exact difference between Adapter and Proxy patterns?

Supun Wijerathne picture Supun Wijerathne · Jun 8, 2016 · Viewed 11.6k times · Source

As I understood both Adapter and Proxy patterns make two distinct/different classes/objects compatible with each for communication. And both of them are Structural patterns. I am getting that both of them are pretty much similar with each other.

Can some one explain what exactly make(s) them different?

EDIT: I went through this question. But I'd rather like to have a close comparison between Adapter and Proxy.

Answer

Ravindra babu picture Ravindra babu · Jun 8, 2016

Adapter:

  1. It allows two unrelated interfaces to work together through the different objects, possibly playing same role.
  2. It modifies original interface.

UML diagram:

enter image description here

You can find more details about this pattern with working code example in this SE post:

Difference between Bridge pattern and Adapter pattern

Proxy:

Proxy provide a surrogate or place holder for another object to control access to it.

UML diagram:

enter image description here

There are common situations in which the Proxy pattern is applicable.

  1. A virtual proxy is a place holder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object.
  2. A remote proxy provides a local representative for an object that resides in a different address space. This is what the "stub" code in RPC and CORBA provides.
  3. A protective proxy controls access to a sensitive master object. The "surrogate" object checks that the caller has the access permissions required prior to forwarding the request.
  4. A smart Proxy provides sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand

For working code, have a look at tutorialspoint article on Proxy.

Key differences:

  1. Adapter provides a different interface to its subject. Proxy provides the same interface
  2. Adapter is meant to change the interface of an existing object

You can find more details about these patterns in sourcemaking articles of proxy and adapter articles.

Other useful articles: proxy by dzone