Design pattern prototype (prototype)

xiaoxiao2021-04-04  248

Definition: Specify the type of the object with a prototype instance and create a new object by copying these prototypes.

Prototype mode allows an object to create another customable object, do not need to know any details of how to create, the working principle is: By passing a prototype object to the object to be created, this object to be created by requesting prototype Objects copy them to implement creation.

How to use it? Because the clone () method in Java provides the clone of the object (specific to Clone ()), the prototype mode achieves a bit 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);}}}}}}}}}}}}}}}}

There are two concreteprototypes:

Public Class Soupspoon Extends AbstractSpoon {PUBLIC SOUPSPOON () {setspoonname ("Soup Spoon");}}

Public Class Saladspoon Extends AbstractSpoon {PUBLIC SALADSPOON () {setspoonname ("salad spoon");}}

Call the prototype mode is very simple:

AbstractSpoon spoon = new Soupspoon (); AbstractSpoon Spoon = new saladspoon ();

Of course, you can also create an ABSTRACTSPOON instance in conjunction with plant mode.

The prototype mode in Java becomes the use of the Clone () method, due to the pure object-oriented characteristics of Java, make it very nature in Java, which is almost a bitter. This is reflected in many modes, such as Interactor traversal mode.

转载请注明原文地址:https://www.9cbs.com/read-131827.html

New Post(0)