Search code examples
c#proxy-pattern

Understanding Proxy Pattern in C#


Suppose if I am trying to access a method of a class through some other class like this

class SuperClass
    {
        public interface ISubject
        {
            void Print();
        }
        private class Subject : ISubject
        {
            public void Print()
            {
                Console.WriteLine("this is a print");
            }
        }
       public class Proxy {
            ISubject subject;
            public void CallOtherMethod() {
                subject = new Subject();
                subject.Print();
            }
        }
    }
    class Client: SuperClass
    {
        static void Main() {
            Proxy proxy = new Proxy();
            proxy.CallOtherMethod();
        }
    } 

is this called as a proxy Class? or does it Require to have a interface as an reference then we have to call the method? for instance like this

class SuperClass
    {
        public interface ISubject
        {
            void Print();
        }
        private class Subject : ISubject
        {
            public void Print()
            {
                Console.WriteLine("this is a print");
            }
        }
        public class Proxy : ISubject
        {
            ISubject subject;
            public void Print()
            {
                subject = new Subject();
                subject.Print();
            }
        }
    }
    class Client : SuperClass
    {
        static void Main()
        {
            ISubject proxy = new Proxy();
            proxy.Print();
        }
    }

Solution

  • Usually, the Proxy pattern is aimed for Interception. That is, catching the call to some (or all) methods of some type and performing some operation before / after the actual call. To achieve that, the Proxy has to inherit from the target type.

    For example:

    public class Subject
    {
        public virtual void Print()
        {
            Console.WriteLine("this is a print");
        }
    }
    
    public class SubjectProxy : Subject
    {
        public override void Print()
        {
            Console.Write("Before calling base.Print()");
            base.Print();
            Console.Write("After calling base.Print()");
        }
    }
    

    Now, when at some point in your code you're expecting a Subject, you may actually get a SubjectProxy and still treat it as Subject:

    public Subject GetSubject()
    {
        return new SubjectProxy();
    }
    
    Subject subject = GetSubject();
    subject.Print(); // would use the proxied method
    

    (That's not to say that the only way to achieve interception is through inheritance. I presume there are Proxy flavors that use variations of composition / decoration to achieve that)