Java Prototyping mode (prototype mode)

Source: Internet
Author: User
Tags object object

Prototype Schema Definition: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototypes.

The prototype mode allows an object to create another customizable object without having to know the details of how to create it, by passing a prototype object to the object that is being created, which creates the object by requesting the prototype object to copy themselves to implement the creation.

How to use prototype mode

Because the Clone () method is provided in Java to implement the cloning of an object, the prototype pattern implementation suddenly becomes simple. Take the spoon as an example:

 Public Abstract classAbstractspoonImplementscloneable{String spoonname; Public voidSetspoonname (String spoonname) { This. Spoonname =Spoonname;}  PublicString Getspoonname () {return  This. Spoonname;}  PublicObject Clone () {Object Object=NULL; Try{Object=Super. Clone (); } Catch(Clonenotsupportedexception exception) {System.err.println ("Abstractspoon is not cloneable"); }returnobject;}}

There are two specific implementations (CONCRETEPROTOTYPE):

 Public class extends abstractspoon{   public Soupspoon () {setspoonname ("Soup Spoon");}}  Public class extends abstractspoon{   public Saladspoon () {setspoonname ("Salad Spoon");}}


Calling prototype mode is simple:

Newnew saladspoon ();


Of course, you can also combine Factory mode to create Abstractspoon instances.

In Java, the prototype pattern becomes the use of the Clone () method, because Java's pure object-oriented nature makes it natural to use design patterns in Java, both of which are almost seamless. This is reflected in many patterns, such as interator traversal mode.

Java Prototyping 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.