public class Basespoon implements cloneable {//spoon spoon, spoon string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} @Overrideprotected Basespoon Clone () throws Clonenotsupportedexception {System.out.println ("clone a Basespoon"); Basespoon Object = Null;try {object = (Basespoon) super.clone ();} catch (Clonenotsupportedexception e) {E.printstacktrace (); System.err.println ("Basespoon is not cloneable");} return object;}}
public class Saladspoon extends Basespoon {public Saladspoon () {setName ("salad Spoon");//Salad Spoon}}
public class Soupspoon extends Basespoon {public Soupspoon () {setName ("Soup Spoon");//tablespoons}}
/* Prototype mode * Specify the kinds of objects created with the prototype instance, and create new objects by copying them. * Prototype prototype mode is a creation design pattern, prototype mode allows an object to create another customizable object without knowing the details of how to create it, * works by passing a prototype object to the object to be created, The objects to be created are created by requesting the prototype object to copy them themselves. * Embodied as Clone () object in Java */public class Test {public static void main (string[] args) throws Clonenotsupportedexception {//Gen Build prototype Basespoon soup1 = new Soupspoon (); Basespoon salad1 = new Saladspoon ();//clone prototype gets the object Soupspoon soup2 = (soupspoon) soup1.clone (); Saladspoon salad2 = (saladspoon) salad1.clone ();//output clone after prototype and corresponding new object name System.out.println ("clone:" + soup1.getname () + "-" + soup2.getname ()); System.out.println ("Clone after:" + salad1.getname () + "-" + salad2.getname ()); Soup1.setname ("Soup1 spoon"); salad1.setname ("Salad1 spoon"); Soup2.setname ("soup2 spoon"); Salad2.setname ("salad2 spoon"); System.out.println ("After property re-assignment:" + soup1.getname () + "-" + soup2.getname ()); System.out.println ("After property re-assignment:" + salad1.getname () + "-" + salad2.getname ());}}
Java Implementation Prototype (PROTOTYPE) mode