What is the Ghost Design Pattern?

前端 未结 4 467
臣服心动
臣服心动 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:12

    It's not in GOF nor Fowler PoEAA, the only thing I can think of it as something similar its a Proxy for lazy loading.

    0 讨论(0)
  • 2021-01-04 09:15

    Ghosts are mentioned in PoEAA, pp 202, 206-14. A ghost is a lazy loaded object that contains just enough info to instantiate itself on demand. They can be useful because they can trigger a bulk load of similar ghosts on the first access if they register themselves with a loader (dunno if Fowler mentions that bit though).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 09:23

    The only reference I've ever heard to a Design Pattern and 'Ghost' is in Lazy-Loading.

    Since Lazy-loading involves only loading the object when it's actually needed, you can think of it as a 'Ghost' until then. You can see its outline, but can't really use it until it's loaded.

    0 讨论(0)
提交回复
热议问题