Agency model-making clothes for others

  Proxy mode definition: provide a proxy for other objects to control access to this object.

  Two use cases of Proxy mode:

  • The remote proxy provides local representation for an object in different address spaces, which can hide the fact that an object exists in different address spaces.
  • The virtual agent creates expensive objects as needed, and uses it to store real objects that take a long time to instantiate to optimize performance.
  • A security agent is used to control the permissions of real objects when they are accessed.
  • Intelligent guidance, when calling the real object, the agent handles other things.

1. The structural
  decoration pattern of the pattern mainly includes the following roles.

  • Subject class: defines the common interface of RealSubject and Proxy, so that Proxy can be used when RealSubject is used.
  • RealSubject class: defines the real entity represented by Proxy.
  • Proxy class: save a reference so that the proxy can access the entity, and provide an interface that is the same as the subject's interface, so that the proxy can be used to replace the entity.

2. Example code

  Subject class

    abstract  class SUBJECT
    {
    
    
        public abstract void Request();
    }

  RealSubject class

    class RealSubject:SUBJECT 
    {
    
    
        public override void Request()
        {
    
    
            Console.WriteLine("真实的请求");
        }
    }

  Proxy class

    class Proxy:SUBJECT 
    {
    
    
        RealSubject realSubject; 
        public override void Request()
        {
    
    
            if(realSubject ==null)
            {
    
    
                realSubject = new RealSubject();
           }
            realSubject.Request();
        }
    }

  Client code

    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Proxy proxy = new Proxy();
            proxy.Request();
            Console.ReadLine();
        }
    }

Guess you like

Origin blog.csdn.net/CharmaineXia/article/details/110076599