Prototype of Design Pattern)

Source: Internet
Author: User

Prototype mode definition:
Use a prototype instance to specify the object type and copy the prototype to create a new object.

The Prototype mode allows an object to create another custom object without any details. The working principle is: pass a Prototype object to the object to be created, the objects to be created are created by requesting the prototype objects to copy themselves.

How to use it?
Because the clone () method is provided in Java to clone objects, Prototype implementation becomes very simple.

Take a spoon as an example:

Public abstract class AbstractSpoon implements Cloneable
{
String spoonName;

Public void setSpoonName (String spoonName) {this. spoonName = spoonName ;}
Public String getSpoonName () {return this. spoonName ;}

Public Object clone ()
{
Object object = null;
Try {
Object = super. clone ();
} Catch (CloneNotSupportedException exception ){
System. err. println ("AbstractSpoon is not Cloneable ");
}
Return object;
}
}

There is a specific implementation (ConcretePrototype ):

Public class SoupSpoon extends actspoon
{
Public SoupSpoon ()
{
SetSpoonName ("Soup Spoon ");
}
}

It is easy to call the Prototype mode:

AbstractSpoon spoon = new SoupSpoon ();
AbstractSpoon spoon2 = spoon. clone ();

Of course, you can also create a AbstractSpoon instance in the factory mode.

In Java, the Prototype mode becomes the use of the clone () method. The pure object-oriented feature of Java makes it natural to use the design mode in Java, the two are almost integrated. This is reflected in many modes, such as the Interator traversal 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.