A book is given at the end of the article! Talk about the application of prototype mode in JAVA practical development (with source code + interview questions)

Author's homepage : Designer Xiao Zheng
About the author : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, committed to enterprise digital transformation, CSDN blog expert, Blue Bridge cloud course certified instructor.

This article explains the prototype pattern in Java design patterns and gives sample code. The main purpose of the prototype pattern is to create new objects by copying or cloning existing objects without relying on an explicit instantiation process.

Insert image description here


1. Let’s talk about what is object cloning?

Before learning the prototype pattern, you must first understand the concept of object cloning.

In Java, object cloning means creating a copy of an existing object\color{red}{Object cloning means creating a copy of an existing object}Object cloning refers to creating a copy of an existing object . Object cloning is usually used to create a new object of the same state without affecting the original object.

Object cloning in Java can be achieved by implementing Cloneableinterfaces and overriding clone()methods.

When using cloning, a copy of an object can be created using the clone() method, which returns a new object with the same property values ​​as the original object.

The method in Java clone()performs a shallow copy, which means that the cloned object and the original object share the same reference type fields. If you need to implement a deep copy, that is, a copy of the cloned object and all its reference type fields, you need to do it in the clone()method Handle accordingly.

Insert image description here


2. Let’s talk about what deep copy and shallow copy are, and what’s the difference?

In Java, object copy can be divided into two methods: shallow copy and deep copy\color{red}{Object copy can be divided into two methods: shallow copy and deep copy}Object copy can be divided into two methods: shallow copy and deep copy . The difference between them lies in whether a copy of the original object is created when copying the object, and how the reference type fields are processed.

2.1 Deep copy

Deep copy refers to creating a new object with exactly the same field values ​​as the original object, including reference type fields. In a deep copy, not only the basic type fields of the object are copied, but also a new object is created to store a copy of the reference type fields. This means that modifying the reference type field of the copied object will not affect the reference type field of the original object, since they refer to different objects.

2.2 Shallow copy

Shallow copy means creating a new object whose field values ​​are exactly the same as the original object, but for reference type fields, they share the same reference. In other words, shallow copy only copies the basic type fields in the object, and for reference type fields, only the reference is copied without creating a new object.
In a shallow copy, modifying the reference type field of the copied object will affect the reference type field of the original object. This is because the original object and the copied object share the same reference, so they point to the same memory address.

2.3 Section

There are many ways to implement deep copy. The more commonly used methods include the following 3 33 o'clock.

  • By implementing Serializablethe interface, deep copying is implemented using object serialization and deserialization.
  • Use Cloneableinterfaces and overridden clone()methods to implement deep copies.
  • In clone()the method, in addition to calling super.clone()the copy object's basic type fields, a separate deep copy process is also required for the reference type fields.

To sum up, a shallow copy only copies references to the object's basic type fields and reference type fields, while a deep copy copies a copy of the object's basic type fields and reference type fields.

Therefore, using deep copy is a more appropriate choice when it is necessary to preserve object independence and avoid modification of the original object.

Insert image description here


3. How to solve the performance problem of java object copy

In Java, object copying may face performance problems, especially when dealing with large objects or complex object graphs. The following are some methods that can help solve Java object copying performance problems and provide a reference for students.

  1. Use the prototype pattern : create new objects by copying or cloning existing objects without relying on an explicit instantiation process, thereby avoiding the overhead of directly creating new objects. The prototype pattern can be achieved by implementing interfaces and overriding methods Cloneable.clone()

  2. Use shallow copy : If you only need to copy the basic type fields of the object, and you can share the reference type fields, then shallow copy is a more efficient choice. Shallow copy only involves the copying of fields, so it is faster than deep copy.

  3. Use a constructor : Manually write a constructor to create a new object based on the properties of the original object. This way you can avoid the overhead of calling clone()methods or implementing Cloneableinterfaces.

  4. Using serialization and deserialization : Deep copying can be achieved using the serialization and deserialization mechanism of Java objects. By serializing the object into a byte stream and then deserializing it into a new object, the object and all its reference fields can be created. A completely independent copy, but serialization and deserialization will also bring certain performance overhead.

  5. Use third-party libraries : Some third-party libraries provide more efficient object copy implementations. For example, Apache Commonsthe library provides SerializationUtils.clone()a method for quickly implementing deep copies of objects.

  6. Use an object pool : If you need to copy objects frequently, you can consider using an object pool. The object pool creates a set of objects in the initial stage, and obtains and returns objects from the pool when needed to avoid frequently creating and destroying objects.

  7. Consider refactoring : Sometimes performance issues can stem from the design of the object itself. In some cases, performance can be improved by optimizing the object's structure or reducing unnecessary fields.

Insert image description here


4. Learn what the prototype pattern is

Prototype pattern is a creational design pattern\color{red}{Prototype pattern is a creational design pattern}Prototype pattern is a creational design pattern whose main purpose is to create new objects by copying or cloning existing objects without relying on an explicit instantiation process.

The prototype pattern creates new objects by copying the state of existing objects, thereby avoiding the overhead of directly creating new objects. The prototype pattern can be implemented by implementing Cloneableinterfaces and overriding clone()methods.

In the prototype pattern, the prototype object, as the copied object, can be called a prototype . The clone method is the core part of the prototype pattern, which defines how to copy the prototype object. With the clone method we can create a new object with the same state as the prototype object.

The main advantage of the prototype pattern is that objects can be created dynamically at runtime\color{red}{The main advantage of the prototype pattern is that objects can be dynamically created at runtime}The main advantage of the prototype pattern is that it can dynamically create objects at runtime , avoiding the explicit instantiation process and improving the efficiency of object creation. It also provides a simple way to create objects with the same state, by modifying the cloned object to meet different needs. In addition, the prototype mode can also hide the details of object creation, decoupling the client code from the concrete class.

But there are some issues you need to pay attention to when using prototype mode. First of all, cloned objects may contain references to other objects, which may lead to duplication of the object graph and need to be handled with special care. Secondly, the cloning process may be more complicated than directly creating the object, and a reasonable implementation of the cloning method is required .

The prototype pattern provides a simple and efficient way to create objects that can dynamically create new objects with the same state at runtime. It is very useful when you need to create similar objects or hide the details of object creation.

Insert image description here


5. Getting Started with Prototype Mode

The following is a Java code example using prototype mode. Please copy it to local execution.

// 原型接口
interface Prototype extends Cloneable {
    
    
    Prototype clone();
}

// 具体原型类
class ConcretePrototype implements Prototype {
    
    
    private String name;

    public ConcretePrototype(String name) {
    
    
        this.name = name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getName() {
    
    
        return name;
    }

    @Override
    public Prototype clone() {
    
    
        try {
    
    
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
    
    
            e.printStackTrace();
            return null;
        }
    }
}

// 客户端代码
public class Client {
    
    
    public static void main(String[] args) {
    
    
        ConcretePrototype prototype = new ConcretePrototype("Prototype 1");
        System.out.println("Original object: " + prototype.getName());

        ConcretePrototype clonedObject = (ConcretePrototype) prototype.clone();
        System.out.println("Cloned object: " + clonedObject.getName());

        clonedObject.setName("Prototype 2");
        System.out.println("Modified cloned object: " + clonedObject.getName());
    }
}

In the above example, we defined a prototype interface Prototype, which contains a clone()method to copy its own object.

Then, we create a concrete prototype class ConcretePrototype, implement Prototypethe interface, and override clone()the method.

In the client code, we first create a prototype object prototype, and then clone()copy the prototype object by calling the method to get a cloned object clonedObject.

By modifying the properties of the cloned object, we can verify that the cloned object and the prototype object are independent of each other and do not affect each other.


6. Application scenarios of prototype mode

Prototype pattern is usually in the following 3 3It is used in 3 types of development scenarios, please students have a simple understanding.

  1. The cost of creating an object is high, for example, it involves time-consuming operations such as database operations and network requests.
  2. The object to be created has similar attributes to the existing object, and only some attributes need to be modified.
  3. The details of object creation need to be hidden, decoupling client code from concrete classes.

Of course, there are still some application scenarios that require the use of prototype mode.

  1. Creation of complex objects : When the process of creating a complex object is tedious or time-consuming, you can use the prototype pattern to copy an existing object to avoid repeated creation.
  2. Prototype registry : Using the prototype pattern, you can create a collection of objects and copy existing objects from the collection when needed to improve object creation efficiency.
  3. An alternative to the factory method pattern : The prototype pattern can be used as an alternative to the factory method pattern. When the objects that need to be created have the same base class or interface, and only some properties need to be modified, the prototype pattern is more flexible than the factory method pattern.

In short, the prototype mode is suitable for objects with high creation costs, complex creation processes, or objects that need to hide the creation details. Creating new objects by cloning existing objects can improve the efficiency of object creation, and can also flexibly meet different needs .

Insert image description here


7. Prototype mode interview questions

1. What is prototype mode? \color{red}{1. What is prototype mode? }1. What is prototype mode?

Prototype pattern is a creational design pattern that creates new objects by copying or cloning existing objects without relying on an explicit instantiation process.

2. How to implement prototype mode? \color{red}{2. How to implement prototype mode? }2. How to implement prototype mode?

In Java, the prototype pattern can be implemented by implementing Cloneableinterfaces and overriding clone()methods. clone()Methods can copy the state of an existing object and create a new object with the same state as the prototype object.

3. What is the difference between the cloning method and the construction method? \color{red}{3. What is the difference between the cloning method and the construction method? }3. What is the difference between the clone method and the construction method?

The clone method creates a new object based on an existing object, while the constructor method creates a new object by instantiating a class. The clone method copies the state of an existing object, while the constructor method requires manually setting the state of the new object.

4. What are the advantages of prototype mode? \color{red}{4. What are the advantages of prototype mode? }4. What are the advantages of prototype mode?

The prototype mode can dynamically create objects at runtime, avoiding the explicit instantiation process and improving the efficiency of object creation. It also provides an easy way to create objects with the same state, and can hide the details of object creation, decoupling client code from concrete classes.

5. What are the applicable scenarios for the prototype mode? \color{red}{5. What are the applicable scenarios for prototype mode? }5. What are the applicable scenarios for the prototype mode?

The prototype pattern is suitable for objects that are expensive to create, have a complex creation process, or need to hide creation details. Some common use cases include the creation of complex objects, prototype registries, and as a replacement for the factory method pattern.

6. What are the limitations of the prototype model? \color{red}{6. What are the limitations of the prototype mode? }6. What are the limitations of the prototype model?

When using the prototype pattern, you need to be aware that cloned objects may contain references to other objects, which may lead to duplication of the object graph and require special care. The cloning process may be more complicated than directly creating the object, and requires a reasonable implementation of the cloning method.


8. Benefits at the end of the article

In order to give back to the fans for their great support, the blogger won the qualification to participate in the event of the publishing house, and together with Tsinghua University Press, they will send books to fans!

The first issue given to fans is "Java from Beginner to Master (7th Edition)", a classic introduction to Java and the entry choice of 950,000 Java programmers. The book introduction is as follows.

From the perspective of beginners, this book explains in detail the knowledge needed to use Java language for program development through easy-to-understand language and colorful examples. All the knowledge in the book is explained with specific examples, and the involved program codes are given detailed comments, which can help readers easily understand the essence of Java program development and quickly improve development skills.

Book purchase links: JD.com , Dangdang.com .

Insert image description here


Activity reward: "Java from entry to mastery (7th edition)" \color{red}{"Java from entry to mastery (7th edition)"}" J a v a from Beginner to Master (7th Edition )" comes with free shipping.
How to participate:Like + favorite + comment on this blog to participate \color{red}{Like + favorite + comment on this blog to participate}like+collect+Get involved by commenting on this blog .
Draw date: September 12, 2023.
Notification method: CSDN private message.


Insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132714587