Q: What are design patterns

Slowly: Design pattern is a solution for common scenarios in system service design, which can solve common problems encountered in the development of functional logic. Design pattern is not limited to the final implementation scheme, but in this conceptual pattern, to solve the code logic problems in system design.

Q: What is prototype mode

Slow: The prototype pattern mainly solves the tedious problem of creating repetitions. This pattern implements an interface for creating a clone of the current object, avoiding problems such as reassignment at creation time.

Q: Get on the code!

Slowly: ok, let’s simulate the clone graph.

Public abstract class Shape implements Cloneable {protected String id; protected String type; abstract void draw(); public String getType() { return type; } public String getId() { return id; } public void setId(String id) { this.id = id; } } public Shape clone() { Shape clone = null; try { clone = (Shape) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; }Copy the code

Specific graphics:

public class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println(type); } } --- public class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println(type); }}Copy the code

Clone object

public class Demo { public static void main(String[] args) { Circle circle = new Circle(); circle.setId("1"); Circle circleClone = circle.clone(); // clone the same object Square Square = new Square(); square.setId("2"); Square squareClone = square.clone(); // Clone the same object}}Copy the code

Q: What are the pros and cons of this model?

Slow: The advantages of the prototype pattern include ease of creating complex objects and avoiding repeated initialization. Disadvantages: If the object class includes a copy of circular references, and if the object class uses a copy of deep objects, the code logic of this approach becomes very complicated.