Problem

An application needs to support certain resource-hungry objects and operations. We would like to avoid instantiating such objects or performing such operations until they are needed.

Solution

Provide a placeholder shell object that can control access to the real object.

Related Patterns

Discussion

There are several common use cases of the Proxy pattern:

Examples

A debit card is a real-world Proxy for money held in a checking account. It can be used as cash in most cases, as it is a good surrogate for physical money. It controls access to the funds in the account.

Code

Here, the ProxyPlaceholder will hold a dummy object until DBConnection is implemented. Additionally, once it is implemented, it will be the interface to that DBConnection. We can use that to interface with the database, changing nothing once it's implemented.

class ProxyPlaceholder{
  DBConnection db;
public:
  ProxyPlaceholder(){db = new DBConnection;}
  getCon(){return db;}
}
int main(){
  string query = "select * from PERSONS";
  ProxyPlaceholder db = new ProxyPlaceholder();
  db->query(query);
}