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...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...