Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Proxy design pattern.
Proxy pattern is a structural pattern that provides a substitute or placeholder for another object through which that object can be controlled. This pattern implements a mechanism that acts as an intermediary between the client and a target object and allows the client to communicate with the target object indirectly through the Proxy object. The main purpose of this pattern is to provide access to control an object without using it directly.
The proxy design pattern consists of three components:
1. Proxy: This object is a substitute for the original object that acts as a substitute for the desired object. This object has the same features as the main object, and by using them, commands are transferred to the main object.
2. Target: This object is the main object that the proxy modifies.
3. Client: This is the object that interacts with the proxy to access the desired object.
Here is an example of a proxy pattern in C#:
public interface IImage
{
void Display();
}
public class RealImage : IImage
{
private string _filename;
public RealImage(string filename)
{
_filename = filename;
LoadFromDisk();
}
public void Display()
{
Console.WriteLine($"Displaying {_filename}");
}
private void LoadFromDisk()
{
Console.WriteLine($"Loading {_filename} from disk");
}
}
public class ProxyImage : IImage
{
private RealImage _realImage;
private string _filename;
public ProxyImage(string filename)
{
_filename = filename;
}
public void Display()
{
if (_realImage == null)
{
_realImage = new RealImage(_filename);
}
_realImage.Display();
}
}
public class Client
{
private IImage _image;
public Client(IImage image)
{
_image = image;
}
public void DisplayImage()
{
_image.Display();
}
}
// Usage
var proxyImage = new ProxyImage("test.jpg");
var client = new Client(proxyImage);
client.DisplayImage();
In this example, IImage is the interface that the proxy and the actual image implement. RealImage is the target object that loads an image from disk and displays it. ProxyImage is a proxy object that binds to the real image. When the Display method is called on the proxy object, it checks to see if the actual image has been created yet. If not, it creates the actual image and then calls the Display method on it.
Finally, we can execute the desired processes through the Client.
To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.
I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.
leave a comment