6.7. Prototype model

发布时间 :2025-10-25 12:24:48 UTC      

The prototype pattern (Prototype Pattern) is used to create duplicate objects while ensuring performance. This type of design pattern is a creative pattern, which provides the best way to create objects.

This pattern implements a prototype interface that is used to create a clone of the current object. This mode is used when the cost of creating an object directly is high. For example, an object needs to be created after a costly database operation. We can cache the object, return its clone on the next request, and update the database when needed to reduce database calls.

6.7.1. Introduction

意图: Specify the type of object to be created with prototype instances, and create new objects by copying these prototypes.

主要解决: Build and delete prototypes at run time.

何时使用: 1. When a system should be created, constructed and represented independently of its products. 2. When the class to be instantiated is specified at run time, for example, through dynamic loading. 3. To avoid creating a factory class hierarchy parallel to the product class hierarchy. 4. When an instance of a class can only have one of several different combinations of states. It may be more convenient to build a corresponding number of prototypes and clone them than to instantiate the class manually with the appropriate state each time.

如何解决: Make use of an existing prototype object to quickly generate the same instance as the prototype object.

关键代码: 1. Realize the cloning operation, inherit Cloneable in JAVA and rewrite clone (). In .NET, you can use the MemberwiseClone () method of the Object class to achieve shallow copy of the object or serialization to achieve deep copy. 2. The prototype pattern is also used to isolate the coupling relationship between users of class objects and specific types (volatile classes). It also requires these “volatile classes” to have a stable interface.

应用实例: 1. Cell division. 2. The Object clone () method in JAVA.

优点: 1. Performance improvement. 2. Evade the constraints of the constructor.

缺点: 1. Equipped with cloning methods, you need to consider the function of the class as a whole, which is not very difficult for new classes, but not necessarily easy for existing classes, especially when a class references an indirect object that does not support serialization, or when the reference contains a circular structure. 2. The Cloneable interface must be implemented.

使用场景: 1. Resource optimization scenario. 2. Class initialization needs to digest a lot of resources, including data, hardware resources, and so on. 3. Scenarios of performance and security requirements. 4. Generating an object through new requires very tedious data preparation or access permissions, then you can use the prototype pattern. 5. A scene with multiple modifiers for one object. 6. When an object needs to be provided for other object access, and each caller may need to modify its value, you can consider using prototype mode to copy multiple objects for caller use. 7. In a real project, the prototype pattern rarely appears alone, usually with the factory method pattern, creating an object through the clone method and then providing it to the caller by the factory method. The prototype pattern has been integrated with Java, and you can use it at your fingertips.

注意事项: Unlike constructing a new object by instantiating a class, the prototype pattern generates a new object by copying an existing object. Shallow copy implements Cloneable, rewrite, and deep copy by implementing Serializable to read the binary stream.

6.7.2. Realize

We will create an abstract class Shape And expanded. Shape The entity class of the. The next step is to define the class ShapeCache Which stores the shape object in a Hashtable And return their clones when requested.

PrototypePatternDemo Class usage ShapeCache Class to get the Shape Object.

原型模式的 UML 图

6.7.3. Step 1

Create an implementation that implements the Cloneable The abstract class of the interface.

Shape.java

publicabstractclassShapeimplementsCloneable{privateStringid;protectedStringtype;abstractvoiddraw();publicStringgetType(){returntype;}publicStringgetId(){returnid;}publicvoidsetId(Stringid){this.id=id;}publicObjectclone(){Objectclone=null;try{clone=super.clone();}catch(CloneNotSupportedExceptione){e.printStackTrace();}returnclone;}}

6.7.4. Step 2

Create an entity class that extends the abstract class above.

Rectangle.java

publicclassRectangleextendsShape{publicRectangle(){type="Rectangle";}@Overridepublicvoiddraw(){System.out.println("Inside
Rectangle::draw() method.");}}

Square.java

publicclassSquareextendsShape{publicSquare(){type="Square";}@Overridepublicvoiddraw(){System.out.println("Inside
Square::draw() method.");}}

Circle.java

publicclassCircleextendsShape{publicCircle(){type="Circle";}@Overridepublicvoiddraw(){System.out.println("Inside
Circle::draw() method.");}}

6.7.5. Step 3

Create a class, get entity classes from the database, and store them in a Hashtable Medium.

ShapeCache.java

importjava.util.Hashtable;publicclassShapeCache{privatestaticHashtable<String,Shape>shapeMap=newHashtable<String,Shape>();publicstaticShapegetShape(StringshapeId){ShapecachedShape=shapeMap.get(shapeId);return(Shape)cachedShape.clone();}//对每种形状都运行数据库查询,并创建该形状//shapeMap.put(shapeKey,
shape);//例如,我们要添加三种形状publicstaticvoidloadCache(){Circlecircle=newCircle();circle.setId("1");shapeMap.put(circle.getId(),circle);Squaresquare=newSquare();square.setId("2");shapeMap.put(square.getId(),square);Rectanglerectangle=newRectangle();rectangle.setId("3");shapeMap.put(rectangle.getId(),rectangle);}}

6.7.6. Step 4

PrototypePatternDemo Use ShapeCache Class to get the data stored in the Hashtable A clone of the shape in the.

PrototypePatternDemo.java

publicclassPrototypePatternDemo{publicstaticvoidmain(String[]args){ShapeCache.loadCache();ShapeclonedShape=(Shape)ShapeCache.getShape("1");System.out.println("Shape
:"+clonedShape.getType());ShapeclonedShape2=(Shape)ShapeCache.getShape("2");System.out.println("Shape
:"+clonedShape2.getType());ShapeclonedShape3=(Shape)ShapeCache.getShape("3");System.out.println("Shape
:"+clonedShape3.getType());}}

6.7.7. Step 5

Execute the program and output the result:

Shape : Circle
Shape : Square
Shape : Rectangle

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.