DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Design Pattern: Proxy

The Proxy pattern is used to provide a “stand-in” or “substitute” for a real object, controlling access to it. It’s useful when you want to delay the creation of a heavy object or protect access to it by controlling its operations. A common example would be image loading: the Proxy can load a thumbnail or placeholder first and then load the full image when needed.

C# Code Example:

// Interface that defines image operations
public interface IImage
{
    void Display();
}

// Class representing the real image, which is "heavy" to load
public class RealImage : IImage
{
    private string _filePath;

    public RealImage(string filePath)
    {
        _filePath = filePath;
        LoadImage();
    }

    private void LoadImage()
    {
        Console.WriteLine($"Loading image from file {_filePath}...");
    }

    public void Display()
    {
        Console.WriteLine($"Displaying image {_filePath}.");
    }
}

// Proxy class that controls access to the RealImage
public class ProxyImage : IImage
{
    private RealImage _realImage;
    private string _filePath;

    public ProxyImage(string filePath)
    {
        _filePath = filePath;
    }

    public void Display()
    {
        // Load the real image only when needed
        if (_realImage == null)
        {
            _realImage = new RealImage(_filePath);
        }
        _realImage.Display();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Create a proxy image
        IImage image = new ProxyImage("photo.jpg");

        // The real image will only be loaded when it's actually displayed
        Console.WriteLine("Image created, but not loaded yet.");
        image.Display();  // Loading and displaying the real image
        image.Display();  // The image is already loaded, so it just displays
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we have the RealImage class, which represents a “heavy” image that needs to be loaded from a file. The ProxyImage controls access to this real image and loads it only when needed, saving resources. When we call the Display method for the first time, the real image is loaded and displayed; in subsequent calls, the Proxy already has the image loaded and just displays it.

Conclusion:

The Proxy pattern is useful when you need to control access to a heavy or sensitive object. It can delay the creation of objects until they are really needed or control the use of a resource efficiently.

Source code: GitHub

Top comments (1)

Collapse
 
dvalin99 profile image
Domenico Tenace

Okay, it's good article 👏🏻
Thanks for sharing your skills about Proxy pattern 🎉