Original: Curly brace MC(wechat official account: Huakuohao-MC), welcome to share, please keep the source.

The prototype pattern is as simple as making use of the Clonable interface provided by Java to make the objects be replicated. The reason it’s called a prototype pattern is because we copy with a prototype or model. This pattern is often used when the object to be created is complex, we can directly copy an existing object and use it directly. Java deep copy and shallow copy should be considered when using the prototype pattern. Serialization is recommended for deep copy.

For example

Demonstrate the use of the prototype pattern through a graphics cache.

Let’s start with UML:

Below is a simple graphic cache to demonstrate the prototype pattern (shallow copy).

public abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); // The get and set methods are omitted here for length reasons. @Override protected Object clone() { Object clone = null; try{ clone = super.clone(); }catch (CloneNotSupportedException e){ e.printStackTrace(); } return clone; }}Copy the code

Define a Circle to implement Shape

public class Circle extends Shape { public Circle(){ type = "Circle"; } @Override void draw() { System.out.println("Inside Circle::draw() method"); }}Copy the code

Define a graphics buffer that stores the created graphics. When the client needs a new graphic, it copies it directly from the graphics buffer.

public class ShapeCache { private static Map<String,Shape> shapeMap = new HashMap<>(); public static Shape getShape(String shapeId){ Shape cacheShape = shapeMap.get(shapeId); Return (Shape) Cacheshape.clone (); } public static void loadCache(){Circle Circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(),circle); }}Copy the code

The client is used this way

Public Class PrototypePatternDemo {public static void main(String[] args){// Create a new Cirlce and place it in the cache ShapeCache. LoadCache (); CloneShape = ShapeCache. GetShape ("1"); // Use clone to get a new Cirlce Shape. System.out.println("Shape : " + cloneShape.getType() + "ID : " + cloneShape.getId() ); }}Copy the code

conclusion

The prototype pattern is simple and one of the creation patterns, just remember that the prototype pattern uses Cloneable to copy objects.

This paper reference: [www.tutorialspoint.com/design_patt]…

Recommended reading

1. Java concurrent programming stuff (10) — Final summary

2. Common network problem locating tools that programmers should master

3. Do you know how to use Awk

4. Teach you how to build a set of ELK log search operation and maintenance platform

Original: Curly brace MC(wechat official account: Huakuohao-MC) Focus on JAVA basic programming and big data, focus on experience sharing and personal growth.