Java Design pattern prototype mode (prototype mode) Introduction _java

Source: Internet
Author: User

Prototype Pattern Definition: Specifies the type of object to create with a prototype instance, and creates a new object by copying the prototypes.

The prototype mode allows one object to create another customizable object without having to know any details of how it was created, working by passing a prototype object to the object to be created, and creating the object by requesting the prototype object to copy themselves.

How to use prototype mode

Because the Java provides the clone () method to implement the object cloning, the prototype pattern implementation suddenly becomes very simple. Take a spoon for example:

Copy Code code as follows:

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 = null;
try {
Object = Super.clone ();
catch (Clonenotsupportedexception exception) {
System.err.println ("Abstractspoon is not cloneable");
}
return object;
}
}

There are two specific implementations (CONCRETEPROTOTYPE):
Copy Code code as follows:

public class Soupspoon extends abstractspoon{
Public Soupspoon () {
Setspoonname ("Soup spoon");
}
}
public class Saladspoon extends abstractspoon{
Public Saladspoon () {
Setspoonname ("Salad spoon");
}
}

Calling the prototype pattern is simple:

Copy Code code as follows:

Abstractspoon spoon = new Soupspoon ();
Abstractspoon spoon = new Saladspoon ();

Of course, you can also combine factory patterns to create Abstractspoon instances.

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

Related Article

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.