简体   繁体   中英

What is the Ghost Design Pattern?

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 only find snippets on the web in reference to it.

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.

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

它不在GOF和Fowler PoEAA中,我唯一可以认为它类似于它的延迟加载代理。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM