国产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;
    }
}

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

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

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

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

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

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

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

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

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

淺克隆

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

以下是代碼的實(shí)現(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

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

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

關(guān)系如下:

Master Prototype Mode in Five Minutes


深克隆

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

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

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

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

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

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

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;

//孫悟空有七十二變,拔猴毛生成一個(gè)金箍棒
//使用JDK的克隆機(jī)制,
//實(shí)現(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);

            //完成一個(gè)新的對象,底層是使用new創(chuàng)建的一個(gè)對象
            //詳情可以了解readObject方法
            QiTianDaSheng qiTianDaSheng = (QiTianDaSheng) bis.readObject();
            //每個(gè)猴子的生日不一樣,所以每次拷貝的時(shí)候,把生日改一下
            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é)論

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

Master Prototype Mode in Five Minutes

總結(jié)

切記:深和淺,指的是克隆對象里的屬性(引用類型)是否指向同一個(gè)內(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)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles