Skip to main content

Understanding the Proxy Method Design Pattern in C#

 

The Proxy Method design pattern is a structural pattern that provides a surrogate or placeholder for another object to control access to it. The proxy object acts as an intermediary, managing the complexities or restrictions involved in accessing the real object.

Example Without the Proxy Method Pattern

Let's consider a scenario where we have a Video class that represents a video file, and a VideoPlayer class that plays the video. For simplicity, we’ll assume that loading a video file is a time-consuming operation.

using System;

namespace WithoutProxyMethodPattern
{
    // Real Subject
    class Video
    {
        private string _fileName;

        public Video(string fileName)
        {
            _fileName = fileName;
            LoadVideo();
        }

        private void LoadVideo()
        {
            // Simulate expensive operation of loading a video
            Console.WriteLine($"Loading video file {_fileName}...");
            System.Threading.Thread.Sleep(2000); // Simulate delay
        }

        public void Play()
        {
            Console.WriteLine($"Playing video {_fileName}...");
        }
    }

    // Client
    class VideoPlayer
    {
        public void PlayVideo(string fileName)
        {
            Video video = new Video(fileName);
            video.Play();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            VideoPlayer player = new VideoPlayer();
            player.PlayVideo("sample.mp4");
        }
    }
}

Problems in the Non-Pattern Approach

  1. Performance Issues: The Video object is created and loaded immediately, even if the video might not be played. This can lead to unnecessary delays.
  2. Uncontrolled Access: There’s no control over who can access or manipulate the video, potentially leading to security issues or misuse.
  3. Resource Management: Creating and loading large video files can be resource-intensive, leading to high memory and CPU usage.

How the Proxy Method Pattern Solves These Problems

The Proxy Method pattern introduces a proxy object that controls access to the real object. It can delay the creation and initialization of the real object until it is needed, add additional functionality like access control, and manage resources more efficiently.

Revisited Code with Proxy Method Pattern

Let's implement a VideoProxy class that acts as a proxy for the Video class. The proxy will delay the loading of the video file until it is actually needed.

using System;

namespace ProxyMethodPattern
{
    // Subject Interface
    interface IVideo
    {
        void Play();
    }

    // Real Subject
    class Video : IVideo
    {
        private string _fileName;

        public Video(string fileName)
        {
            _fileName = fileName;
            LoadVideo();
        }

        private void LoadVideo()
        {
            // Simulate expensive operation of loading a video
            Console.WriteLine($"Loading video file {_fileName}...");
            System.Threading.Thread.Sleep(2000); // Simulate delay
        }

        public void Play()
        {
            Console.WriteLine($"Playing video {_fileName}...");
        }
    }

    // Proxy
    class VideoProxy : IVideo
    {
        private string _fileName;
        private Video _video;

        public VideoProxy(string fileName)
        {
            _fileName = fileName;
        }

        public void Play()
        {
            if (_video == null)
            {
                _video = new Video(_fileName);
            }
            _video.Play();
        }
    }

    // Client
    class VideoPlayer
    {
        public void PlayVideo(string fileName)
        {
            IVideo video = new VideoProxy(fileName);
            video.Play();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            VideoPlayer player = new VideoPlayer();
            player.PlayVideo("sample.mp4");
        }
    }
}

Benefits of the Proxy Method Pattern

  1. Lazy Initialization: The real Video object is not created until the Play method is called, reducing unnecessary resource consumption.
  2. Access Control: The proxy can restrict or log access to the real object, enhancing security and auditability.
  3. Resource Management: By controlling the creation and destruction of the real object, the proxy can manage resources more efficiently.

Why Can't We Use Other Design Patterns Instead?

  • Decorator Pattern: While the Decorator pattern adds behavior to objects, it does so transparently and does not control access or defer object creation like the Proxy pattern.
  • Adapter Pattern: The Adapter pattern is used to make an object compatible with a different interface. It doesn't control access or manage resource-intensive objects.
  • Facade Pattern: The Facade pattern provides a simplified interface to a complex system. It doesn't involve controlling access to an object or managing object lifecycle.

Steps to Identify Use Cases for the Proxy Method Pattern

  1. Expensive Object Creation: Identify scenarios where creating an object is resource-intensive, and defer its creation until necessary.
  2. Access Control: Use the Proxy pattern when you need to control access to the real object.
  3. Lazy Initialization: When you want to delay the initialization of an object until it's actually needed, the Proxy pattern is a good fit.
  4. Security and Logging: The Proxy pattern is useful for adding security checks and logging around object access.

By understanding and applying the Proxy Method design pattern, you can optimize performance, manage resources better, and control access in your software systems, leading to cleaner and more maintainable code.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...