开发者

Questions about the Prototype Pattern

开发者 https://www.devze.com 2023-02-28 06:49 出处:网络
I am learning about the different design patterns and I have a strong feeling I am missing an essential piece (or pieces) in understanding this particular pattern.

I am learning about the different design patterns and I have a strong feeling I am missing an essential piece (or pieces) in understanding this particular pattern.

In all the websites I have viewed and in the GoF book, I see the clone method. From what I understand, we have some type of object that we can clone when we need varying versions of that object, but we don't want to have to manually create each one using the "new" command (as in Java). This c开发者_开发百科an hide its concrete implementation. So when we clone, we can tweak the clone just a little bit and make it what we need without having to knowing how to originally create that object the hard way. Is this my thinking correct?

I am also told that this can reduce subclassing and subsequently reduce the number of classes you need to make. I don't quite understand this part. Could someone help me grasp this?

My final question is about the abstract factory (or even the factory method) pattern. These factory patterns and the prototype pattern feel like they attempt to hide concrete implementations upon creation of new objects. When is it a good idea to choose one of the other?

Thank you all!


Prototype pattern

Prototype results in a cloned object which is different from the original object. The state of the original is the same as the clone, at the time of cloning. Thereafter each object may undergo state change. You can think of this as something similar photocopying the original and then modifying the photocopy at a few places.

Example

  • DVD duplication: Duplication of the master dvd to create several copies
  • Reporting object: Consider a report object that contains processed information to be passed to the GUI. The original report contains the data in ascending order. Now, using this pattern one can create a similar report but with data sorted in descending order.

Benefits

  • Performance: Cloning (using MemberwiseClone) is considerably less expensive than creating a new object afresh (with new operator). Note that one needs to override the MemberwiseClose() to perform a deep copy.
  • Objects can be cloned very dynamically, without any insistence on up-front instantiation. The first created object can be created at any time in the application execution, and further duplication can take place at any time ahead.

When to use it

  • When the classes to instantiate are specified at run-time, for example, by dynamic loading.
  • When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Comparison with Factory Pattern

Prototype pattern allows an object to create customized objects without knowing their class or any details of how to create them. So, it is this aspect it appears to be a lot like the Factory Method pattern. In both these patterns, the client can create any of the derived class objects without knowing anything about their own structure.

But the difference between the two patterns is the fact that the Factory Method concentrates on creating one object of a non existing object type as a fresh creation (by understanding the exact sub-type of the Creator class). The Prototype pattern uses the class itself, especially the derived class for self duplication action.


Factory Method pattern

In this pattern, the client (or consumer) asks the Creator (or factory) for a specific type of object from a class hierarchy. The Creator method of the factory class delegates the creation of the specific object to the derived classes and returns the object of the class of the type asked by client. In essence, you have a single point of contact for the creation of several objects of a class hierarchy.

You can think of this as going to an airline ticket counter (controller) and asking for a ticket by giving your preference of the ticket type (first class, executive or economy). The user is not concerned with how the ticket is being generated, even though in an object representation the first class and the economy ticket are both derived from the base ticket class.

When to use

  • Flexibility is important (low coupling)
  • Objects can be extended in subclasses
  • There is a specific reason why one subclass would be chosen over another—this logic forms part of the Factory Method.
  • A client delegates responsibilities to subclasses in parallel hierarchies.


Abstract factory pattern

Abstract factory goes a step higher (more abstract) than the factory method pattern. In this case, one can have not just a single, but multiple factories with slight variations. It is responsible for creating objects belonging families of class hierarchies rather than just a single class hierarchy.

A specific Factory class already exists. But the Factory will have slightly varying methods. Each method can produce an instance. The client can choose appropriate method and get the instance.

If you take the example of MVC based perfect Architectural Design, the client will be a Business Controller Class while Concrete Products will all be Business Entities. The Factories are Auxiliary ( Helper) Controllers. They work in association with a request from the Business Controller.

When to use

  • The system is expected to be independent of how its products are created. It may even expect independence on how the products are composed and represented. The term product applies to the finally resulting object that a client developer would need to make use of by invoking its methods.
  • The system that should be configurable with one of the multiple families of products. So the actual selection of the family will not be at coding time but at a later configuration time.
  • The family of products is designed to work always together.
  • The creation is for a library of products. What is cared more here is the relevant interface and not the implementation.


You've got the prototype pattern right by the looks of it.

How it Reduces Subclassing

Lets say you're making MineCraft and you're using the prototype pattern for each different kind of block (e.g. dirt, stone, etc). All the prototype objects are actually of the same class Block, but each object has had different properties set on it so that it looks and behaves differently, for example:

prototypes.dirt = new Block;
prototypes.dirt.texture = new Image("dirt.jpg");
prototypes.dirt.hardness = 1;

prototypes.stone = new Block;
prototypes.stone.texture = new Image("stone.jpg");
prototypes.stone.hardness = 9;

So instead of subclassing where you would write new DirtBlock or new StoneBlock, you would instead write prototypes.dirt.clone() or prototypes.stone.clone(). No subclassing is required, but you still have the option to subclass if need be.

Differences With Factory Pattern

As for when to choose the prototype pattern instead of a factory pattern, there are two situations I can think of where they differ:

  1. You can iterate over a list of prototypes, but you can't iterate over all the methods on an abstract factory^. Continuing from the code above, you could create a random block like so:

    prototypes.allValues().objectAtIndex(rand() % prototypes.size()).clone();

    If you were using the factory method to make blocks, it would be harder to get a random block.

  2. Where creation of an object is expensive, but copying is cheap, the prototype pattern will be more efficient. For example, take this factory method:

    Image loadUserImage() { 
        //loads from disk. will be slow
        return new JPEGImage("path/to/user/image.jpg"); 
    }
    

    If this method is going to be called repeatedly, it would be more efficient to use a prototype like so:

    Image loadUserImage() {
        //copy in memory. will be fast
        return userImagePrototype.clone();
    }
    


^ This is a white lie because you actually can iterate over methods depending on what language you're using, but iterating over an array is still probably a better solution because it's less complex than reflection/introspection.


The gain in efficiency of using a prototype is questionable in my mind. There will be no efficiency gain because in most languages the clone method itself executes a call to new in order to construct a new object instance of itself.

The only benefit that I see in using the prototype pattern is one of convenience, you know that clone will give you an exact copy of the object which frees you from having to set the attributes of the new object to the same values yourself and possibly struggling with deep copy.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号