"Design mode" prototype mode

Source: Internet
Author: User

Prototype mode (Prototype pattern) is used to create duplicate objects while guaranteeing performance. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object.

This pattern implements a prototype interface that is used to create clones of the current object. This pattern is used when the cost of directly creating an object is relatively large. For example, an object needs to be created after a high-cost database operation. We can cache the object, return its clone on the next request, and update the database when needed to reduce the database call.

Introduced

Intent: Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.

Main Solution: build and delete prototypes during run time.

When to use: 1, when a system should be independent of its product creation, composition and presentation. 2, when the class to be instantiated is specified at run time, for example, by dynamic loading. 3. To avoid creating a factory class hierarchy that is parallel to the product class hierarchy. 4. When an instance of a class can have only one of several different state combinations. Building the corresponding number of prototypes and cloning them may be more convenient than manually instantiating the class each time you use the appropriate state.

How to Solve: Use an existing prototype object to quickly generate the same instance as the prototype object.

Key code: 1, the implementation of cloning operations, in JAVA inheritance cloneable, rewrite clone (), in. NET can use the object class's MemberwiseClone () method to implement a shallow copy of objects or by serialization to implement the deep copying PayPal 2. The prototype pattern is also used to isolate the coupling between the user of the class object and the specific type (variable Class), which also requires these "variable classes" to have a stable interface.

Application Example: 1, cell division. 2. The Object Clone () method in JAVA.

Advantages: 1, performance improvement. 2, escape from the constraints of the constructor function.

Cons: 1. The cloning method requires an overall consideration of the function of the class, which is not difficult for a new class, but not necessarily easy for existing classes, especially when a class reference does not support serialization of indirect objects, or when a reference contains a looping structure. 2, must implement the Cloneable interface. 3, Escape from the constraints of the constructor function.

usage Scenario: 1, resource optimization scenario. 2, the class initialization needs to digest very many resources, this resource includes the data, the hardware resources and so on. 3, performance and security requirements of the scene. 4. Creating an object with new requires very tedious data preparation or access, you can use prototype mode. 5, one object multiple modifiers of the scene. 6, an object needs to be provided to other object access, and each caller may need to modify its value, you may consider using prototype mode to copy multiple objects for the caller to use. 7, in the actual project, the prototype pattern rarely appears alone, usually with the factory method pattern appears, through the Clone method to create an object, and then provided by the factory method to the caller. Prototype mode has been seamless with Java, and you can use it handy.

Note: Unlike constructing a new object by instantiating a class, the prototype pattern creates a new object by copying an existing object. Shallow copy implements Cloneable, rewrite, deep copy is read binary stream by implementing Serializable.

Realize

We will create an abstract class shape and an entity class that extends the shape class. The next step is to define the class Shapecache, which stores the Shape objects in a Hashtable and returns their clones when requested.

Prototyppatterndemo, our demo class uses the Shapecache class to get the Shape object.

Step 1

Create an abstract class that implements the clonable interface.

 Public Abstract classShapeImplementscloneable {PrivateString ID; protectedString type; Abstract voidDraw ();  PublicString GetType () {returntype; }       PublicString getId () {returnID; }       Public voidsetId (String id) { This. ID =ID; }       PublicObject Clone () {Object Clone=NULL; Try{Clone=Super. Clone (); } Catch(clonenotsupportedexception e) {e.printstacktrace (); }      returnclone; }}

Step 2

Creates an entity class that extends the above abstract class.

 Public class extends Shape {   public  Rectangle () {     = "Rectangle";   }   @Override   publicvoid  Draw () {      System.out.println ("Inside Rectangle::d Raw () method. " );   }}

 public  class  Square extends   Shape { public   Square () {type  = "Square" ; } @Override  public  void   Draw () {System.out.println ( Inside Square::d Raw () method. "   ); }}
 Public class extends Shape {   public  Circle () {     = "Circle";   }   @Override   publicvoid  Draw () {      System.out.println ("Inside Circle:: Draw () method. " );   }}

Step 3

Create a class, get the entity classes from the database, and store them in a Hashtable .

Importjava.util.Hashtable; Public classShapecache {Private StaticHashtable<string, shape>Shapemap=NewHashtable<string, shape>();  Public Staticshape Getshape (String shapeid) {shape Cachedshape=Shapemap.get (ShapeID); return(Shape) Cachedshape.clone (); }   //run a database query for each shape and create the shape//shapemap.put (ShapeKey, shape); //For example, we want to add three shapes    Public Static voidLoadcache () {Circle Circle=NewCircle (); Circle.setid ("1");      Shapemap.put (Circle.getid (), circle); Square Square=NewSquare (); Square.setid ("2");      Shapemap.put (Square.getid (), square); Rectangle Rectangle=NewRectangle (); Rectangle.setid ("3");   Shapemap.put (Rectangle.getid (), rectangle); }}

Step 4

Prototypepatterndemo uses the Shapecache class to get clones of the shapes stored in Hashtable .

 public  class   Prototypepatterndemo { static  void   main (string[] args) {      Shapecache.loadcache ();      Shape Clonedshape  = (shape) shapecache.getshape ("1" );              System.out.println ( Shape: "+ Clonedshape.gettype ());      Shape clonedShape2  = (shape) shapecache.getshape ("2" );              System.out.println ( Shape: "+ Clonedshape2.gettype ());      Shape ClonedShape3  = (shape) shapecache.getshape ("3" );           System.out.println ( Shape: "+ Clonedshape3.gettype ()); }}

Step 5

Verify the output.

Shape:CircleShape:SquareShape:Rectangle

"Design mode" prototype mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.