Prototype Mode - Prototype
Create more objects of the same type by duplicating (clone, copy) an object of a specified type.
Product interface
We will use the prototype pattern to create objects, and these objects are abstracted as Product
Product also provides a copy method createClone(). It inherits the Cloneable interface.
Note: The createClone() method here is not inherited from Cloneable. There is no method declared in Cloneable. Cloneable is just an interface for marking.
public interface Product extends Cloneable { void use(String str); Product createClone(); }
UnderlinePen class
This is the implementation class of the Product interface, the underscore class.
After passing a string to a specific underscore class, it will print out the string and the underscore
public class UnderLinePen implements Product { /** * underscore character */ private char underLineChar; public UnderLinePen(char ch) { this.underLineChar = ch; } /** * After passing in str, it will print str and underscore */ @Override public void use(String str) { System.out.println("\"" + str + "\""); System.out.print(" "); for (int i = 0; i < str.getBytes().length; i++) { System.out.print(underLineChar); } System.out.println(""); } /** * return a clone */ @Override public Product createClone() { try { return (Product) this.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace (); return null; } } }
UnderLinePenManager类
For unified management of products, he is responsible for registration and cloning
public class UnderLinePenManager { /** * All kinds of pens are registered here, unified management */ private static final HashMap<String, Product> PENS = new HashMap<>(); /** * Registration pen */ public static void register(String name, Product pen) { PENS.put(name, pen); } /** * Take a pen from the registry HashMap with name as the key, and then clone a new one to return */ public static Product createPen(String name) { return PENS.get(name).createClone(); } }
Main
This class is used to run tests
public class Main { static { /** * Register various pens to Manager for unified management */ UnderLinePenManager.register("wave-line" , new UnderLinePen('~')); UnderLinePenManager.register("bee-line" , new UnderLinePen('_')); UnderLinePenManager.register("dotted-line", new UnderLinePen('.')); } public static void main(String[] args) { // Every time you need a certain pen, just clone a copy based on the existing pen // Take out a wavy pen Product anotherPen1 = UnderLinePenManager.createPen("wave-line"); // print with a wavy pen anotherPen1.use("hello world"); } }