国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
淺克隆 " >淺克隆
深克隆 " >深克隆
Home Java javaTutorial Master Prototype Mode in Five Minutes

Master Prototype Mode in Five Minutes

Aug 25, 2023 pm 03:52 PM
java


Hello everyone, I am Lao Tian, ??Today I will share with you the Prototype pattern## in the design pattern. #. Use appropriate life stories and real project scenarios to talk about the design pattern, and finally summarize the design pattern in one sentence.

Master Prototype Mode in Five Minutes

##Story I still remember looking for At work, I accidentally found a relatively beautiful programmer resume template from the Internet, and then the whole class started copying the resume (U disk) like crazy. At the same time, there was also a joke. Several students copied their past resumes without changing the contents or their names. They submitted them to the interviewer (campus recruitment interviewer) as the deadline. Later, everyone should be able to guess the result. Everyone went for internships, and some of them were still looking for jobs.

Feedback from the interviewer at the company and other classmates later: I received several resumes that were exactly the same. When I came back, everyone knew what the problem was after we talked about it. I admitted that I had copied it and submitted it without any changes. Harmful, embarrassing one.

There are two types of resume copies:

  • One is to copy the resume and then modify the information to your own
  • The other is to copy the resume without changing the content.

Prototype pattern definition

Specify the kinds of objects to create using a prototype instance, and create new objects by coping with this prototype

roughly meaning: Specify the types of objects to create using prototype instances, and create new objects by copying these prototypes.

Prototype pattern: Prototype Pattern, which is a creational pattern.

The caller does not need to know any creation details, nor does it need to call the constructor to create the object.

Usage scenarios

The prototype mode has the following usage scenarios:

  • Class initialization consumes more resources
  • An object generated by new requires a very cumbersome process (data preparation, access permissions, etc.)
  • The constructor is more complex
  • When a large number of objects are generated in the loop body
  • In Spring, the prototype pattern is very much used Widely, for example: scope='prototype'

We can encapsulate some getters and setters into a factory method, and then for those who use it, Just call the method, you don't need to know how the getters and setters inside are handled. We can also use the Cloneable interface provided by JDK to achieve fast copying.

Four ways to create objects:

new, reflection, cloning, serialization

Actual case

Have you ever encountered this common situation? It is stipulated in the project that the entity class mapped with the database table cannot be returned to the front end, so the following are usually returned to the front end: Various O, such as: XxxVO, XxxBO, XxxDTO...

The following scene will appear at this time, and everyone may have guessed it.

The following is the UserEntity entity class mapped to the database table.

public class UserEntity {
    private Long id;
    private String name;
    private Integer age;
    //....可能還有很多屬性
    //省略getter setter
}

The UserVO entity class returned to the front end or caller.

public class UserVO {
    private Long id;
    private String name;
    private Integer age;
    //....可能還有很多屬性
    //省略getter setter
}

At this time, the UserEntity found from the database needs to be converted into UserVO and then returned to the front end (or caller).

public class ObjectConvertUtil {

    public static UserVo convertUserEntityToUserVO(UserEntity userEntity) {
        if (userEntity == null) {
            return null;
        }
        UserVo userVo = new UserVo();

        userVo.setId(userEntity.getId());
        userVo.setName(userEntity.getName());
        userVo.setAge(userEntity.getAge());
         //如果還有更多屬性呢?
        return userVo;
    }
}

從這個util類中,我們可以看出,如果一個類的屬性有幾十個,上百個的,這代碼量是不是有點恐怖?

于是,我們通常都會使用一些工具類來處理,比如常見有以下:

BeanUtils.copy();
JSON.parseObject()
Guava工具類
.....

這些工具類就用到了原型模式。

通過一個對象,創(chuàng)建一個新的對象。

也把原型模式稱之為對象的拷貝、克隆。

其實對象的克隆分淺克隆和深克隆,下面我們就來聊聊淺克隆和深克隆。

  • 淺克?。簞?chuàng)建一個新對象,新對象的屬性和原來對象完全相同,對于非基本類型屬性,仍指向原來對象的屬性所指向的對象的內(nèi)存地址。
  • 深克?。簞?chuàng)建一個新對象,屬性中引用的其他對象也會被克隆,不再指向原有對象地址。

我們先來聊聊淺克隆,都喜歡由淺入深。

淺克隆

比如,我現(xiàn)在相對用戶信息User進行克隆,但是User中有用戶地址信息UserAddress屬性。

以下是代碼的實現(xiàn):

//用戶地址信息
public class UserAddress  implements Serializable{
    private String province;
    private String cityCode;

    public UserAddress(String province, String cityCode) {
        this.province = province;
        this.cityCode = cityCode;
    }
}
//用戶信息
public class User implements Cloneable {
    private int age;
    private String name;
    //用戶地址信息
    private UserAddress userAddress;

    //getter setter 省略

    @Override
    protected Object clone() throws CloneNotSupportedException { 
        return super.clone();
    }
}
//測試
public class UserTest {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setAge(20);
        user.setName("田維常");
        UserAddress userAddress = new UserAddress("貴州", "梵凈山");
        user.setUserAddress(userAddress);

        User clone = (User) user.clone();

        System.out.println("克隆前后UserAddress比較:" + (user.getUserAddress() == clone.getUserAddress()));
    }
}

輸出結(jié)果

克隆前后 UserAddress 比較:true

兩個對象屬性 UserAddress 指向的是同一個地址。

這就是所謂的淺克隆,只是克隆了對象,對于該對象的非基本類型屬性,仍指向原來對象的屬性所指向的對象的內(nèi)存地址。

關(guān)系如下:

Master Prototype Mode in Five Minutes


深克隆

關(guān)于深克隆,我們來用一個很經(jīng)典的案例,西游記里的孫悟空。一個孫悟空能變成n多個孫悟空,手里都會拿著一個金箍棒。

按照前面的淺克隆,結(jié)果就是:孫悟空倒是變成很多孫悟空,但是金箍棒用的是同一根。

深克隆的結(jié)果是:孫悟空變成了很多個,金箍棒也變成很多個根。

下面我們用代碼來實現(xiàn):

//猴子,有身高體重和生日
public class Monkey {
    public int height;
    public int weight;
    public Date birthday;
}

孫悟空也是猴子,兵器 孫悟空有個金箍棒:

import java.io.Serializable;
//孫悟空的金箍棒
public class JinGuBang implements Serializable{
    public float  h=100;
    public float  d=10;
    //金箍棒變大
    public void big(){
        this.h *=10;
        this.d *=10;
    }
    //金箍棒變小
    public void small(){
        this.h /=10;
        this.d /=10;
    }
}

齊天大圣孫悟空:

import java.io.*;
import java.util.Date;

//孫悟空有七十二變,拔猴毛生成一個金箍棒
//使用JDK的克隆機制,
//實現(xiàn)Cloneable并重寫clone方法
public class QiTianDaSheng extends Monkey implements Cloneable, Serializable {

    public JinGuBang jinGuBang;

    public QiTianDaSheng() {
        this.birthday = new Date();
        this.jinGuBang = new JinGuBang();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return this.deepClone();
    }

    //深克隆
    public QiTianDaSheng deepClone() {
        try {
            //內(nèi)存中操作完成、對象讀寫,是通過字節(jié)碼直接操作
            //與序列化操作類似
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream bis = new ObjectInputStream(bais);

            //完成一個新的對象,底層是使用new創(chuàng)建的一個對象
            //詳情可以了解readObject方法
            QiTianDaSheng qiTianDaSheng = (QiTianDaSheng) bis.readObject();
            //每個猴子的生日不一樣,所以每次拷貝的時候,把生日改一下
            qiTianDaSheng.birthday = new Date();
            return qiTianDaSheng;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //淺克隆,就是簡單的賦值
    public QiTianDaSheng shalllowClone(QiTianDaSheng target) {
        QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();
        qiTianDaSheng.height = target.height;
        qiTianDaSheng.weight = target.weight;

        qiTianDaSheng.jinGuBang = target.jinGuBang;
        qiTianDaSheng.birthday = new Date();
        return qiTianDaSheng;

    }
}

接著我們就來測試一下:

public class DeepCloneTest {
    public static void main(String[] args) {
        QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();
        try {
            QiTianDaSheng newObject = (QiTianDaSheng) qiTianDaSheng.clone();
            System.out.print("深克隆后 ");
            System.out.println("金箍棒是否一直:" + (qiTianDaSheng.jinGuBang == newObject.jinGuBang));
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
        QiTianDaSheng newObject=qiTianDaSheng.shalllowClone(qiTianDaSheng);
        System.out.print("淺克隆后 ");
        System.out.println("金箍棒是否一直:" + (qiTianDaSheng.jinGuBang == newObject.jinGuBang));
    }
}

輸出結(jié)果為:

深克隆后 金箍棒是否一直:false
淺克隆后 金箍棒是否一直:true

結(jié)論

深克隆后每個孫悟空都有自己的金箍棒,而淺克隆后每個孫悟空用的金箍棒實質(zhì)上還是同一根。

Master Prototype Mode in Five Minutes

總結(jié)

切記:深和淺,指的是克隆對象里的屬性(引用類型)是否指向同一個內(nèi)存地址。

為了更深刻的理解深克隆和淺克隆,我們回答文中的簡歷拷貝的故事。

  • Deep copy: Copy a resume, and then modify the information in the resume into your own
  • ##Shallow copy: Copy a resume, resume content Completely unchanged

Advantages:

  • Java prototype mode is based on memory binary stream copy, which has better performance than direct new Better.
  • You can use deep cloning to save the object state, save an old copy (clone it), and then modify it, which can serve as an undo function.

Disadvantages:

  • needs to configure the clone method, and needs to modify existing classes during transformation, which violates the "open" principle of closure”.
  • If there are multiple nested references between objects, each layer needs to be cloned.
We have given a comprehensive explanation of the prototype pattern from the aspects of its definition, usage scenarios, real cases, shallow cloning, deep cloning, advantages and disadvantages, etc.

The above is the detailed content of Master Prototype Mode in Five Minutes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to parse JSON in Java? How to parse JSON in Java? Jul 11, 2025 am 02:18 AM

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

See all articles