Technology Sharing

Java Design Pattern (VI) - Prototype Pattern

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. Mode Introduction

Prototype mode:
One of the creational patterns is to create objects based on prototypes, that is, the generation of an object does not have to start from scratch.
Directly clone an object that already has a certain prototype, and then modify it to the required object. Save time in creating objects.

scenes to be used
If the object creation cost is relatively high, for example, the data in an object needs to access the database to obtain;
And the difference between different objects of the same class is not big (most of the fields are the same), in this scenario, you can consider using the prototype mode

2. Prototype Mode

1. Implementation
Shallow copy: only copy the object being copied (that is, copy the properties of the object itself, only the properties of the base class, not the properties of the custom class), rather than copying its reference object (custom class), the reference object points to the same. The clone method provided by the Object class only copies the object itself
Implementation steps:

第一步:定义原型类,需实现Cloneable接口,重写clone方法 super.clone()