What is the virtual proxy design pattern?

The virtual proxy design pattern is used to preserve memory from being allotted to an object that may not be used in the future. Until the object is not used, a light copy of the object (that contains the required details) is created and shown to the user.

Use case

If an entire library of books, with all the details about each book, is loaded from a database, it will consume a lot of RAM, and it is very likely that the user will need to issue or return only one book. The solution, that uses the virtual proxy design pattern, displays only the name, author, and availability of the books when a list of them is displayed. When a book is selected, all of the remaining details will be fetched from the database and shown to the user.

UML diagram

svg viewer

Implementation

The code below is for the virtual proxy design pattern in C++ and Java:

#include <iostream>
using namespace std;
// Abstract class:
class Book{
public:
virtual string getName() = 0;
virtual string getAuthor() = 0;
virtual bool isAvailable() = 0;
virtual void showInfo() = 0;
};
// Original complete class:
class OriginalBook: public Book{
private:
string name, author, description;
int rating;
bool available;
public:
OriginalBook(string n, string a, string d, int r, bool available){
name = n;
author = a;
description = d;
rating = r;
this->available = available;
}
string getName(){
return name;
}
string getAuthor(){
return author;
}
string getDescription(){
return description;
}
int getRating(){
return rating;
}
bool isAvailable(){
return available;
}
void showInfo(){
cout << "..:: COMPLETE BOOK ::.."
<< "\nName: " << name
<< "\nAuthor: " << author
<< "\nDescription: " << description
<< "\nRating: " << rating
<< "\nAvailable: " << available << endl << endl;
}
};
// Light version of OriginalBook:
class ProxyBook: public Book{
private:
string name, author;
bool available;
public:
ProxyBook(string n, string a, bool available){
name = n;
author = a;
this->available = available;
}
string getName(){
return name;
}
string getAuthor(){
return author;
}
bool isAvailable(){
return available;
}
void showInfo(){
cout << "..:: PROXY BOOK ::.."
<< "\nName: " << name
<< "\nAuthor: " << author
<< "\nAvailable: " << available << endl << endl;
}
OriginalBook* click(){
// Setting some default values
// which will be fetched from a database
// in an actual implementation:
string description = "A bestselling novel";
int rating = 3;
// Creating the OriginalBook object
// and returning it:
return new OriginalBook(getName(), getAuthor(), description, rating, isAvailable());
}
};
int main(){
// Creating a ProxyBook
// and showing its info:
Book* book = new ProxyBook("Ice and Fire", "Elia Martell", true);
book->showInfo();
// Requesting the complete object
// and showing the info:
book = ((ProxyBook*)book)->click();
book->showInfo();
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved