Introduction to the Prototype model of Java design patterns

  • 2020-04-01 03:41:28
  • OfStack

The Prototype pattern definition: specifies the type of objects to be created with a Prototype instance, and creates new objects by copying the Prototype.

The Prototype pattern allows one object to create another customizable object without knowing any details of how it was created. This works by passing a Prototype object to the object to be created, and the object to be created creates it by asking the Prototype object to copy it.

How to use the prototype pattern

Because Java provides a clone() method to clone objects, the Prototype pattern implementation suddenly becomes simple. Take the spoon:


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 are two concrete implementations:

public class SoupSpoon extends AbstractSpoon{
 public SoupSpoon(){
  setSpoonName("Soup Spoon");
 }
}
public class SaladSpoon extends AbstractSpoon{
 public SaladSpoon(){
  setSpoonName("Salad Spoon");
 }
}

Calling Prototype mode is simple:


AbstractSpoon spoon = new SoupSpoon();
AbstractSpoon spoon = new SaladSpoon();

You can also create an AbstractSpoon instance in conjunction with the factory pattern.

The use of the Prototype pattern to clone() method in Java has become almost integral to the pure object-oriented nature of Java, which makes it natural to use design patterns in Java. This is reflected in many patterns, such as the Interator traversal pattern.


Related articles: