What is the Ghost Design Pattern?

前端 未结 4 469
臣服心动
臣服心动 2021-01-04 08:58

Someone recently asked a question about the Ghost Design Pattern - I have not seen this before.

What is the Ghost Design Pattern and how is it implemented? I can

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 09:15

    I actually just created one and then realized it was a Ghost pattern after asking a question here in SO. Follow that link for the original PHP code, here's a pseudo-code version:

    // A "cheap" class
    class Namespace_Original
      {
      // The expensive, uninitialised object
      private Original
    
      // The "cheap" data needed to initialize Original
      private Data
    
      // Constructor for the cheap class
      public Namespace_Original(Data)
        {
        this.Data = Data
        }
    
      // Whenever you call a method of Original
      public __call(method_name, method_data)
        {
        // Create the expensive object only the first time it's going to be used
        if (empty(this.Original))
          this.Original = new Original(this.Data);
    
        // Call the Original's method with it's arguments
        this.Original.name( method_data );
        }
      }
    

    When you initialize this cheap class, nothing is created inside it. It's when you actually call a method that the "Original" object gets created, if there was none, and data retrieved from that. It makes you not to initialize Original if you're not going to use it, providing it's an expensive operation.

提交回复
热议问题