【一天一个设计模式】原型模式的学习和理解

本文探讨了原型模式的两种实现方式,包括在类中实现克隆方法以及使用序列化进行克隆。通过示例代码展示了如何在User类和Prototype类中实现深拷贝,并分析了序列化克隆的优缺点,指出其可能带来的性能消耗问题。
摘要由CSDN通过智能技术生成

最初的写法 在类中实现克隆方法 原型模式

可以重写equals和hashcode 反序列化出来的对象地址是不同的equals

User类

为了测试深拷贝,要在需要拷贝的类中加入引用类型

@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class User implements Serializable {
   
    private String username;
    private String password;
}

Prototype类

package design.prototype;

import lombok.*;

import java.io.*;

@NoArgsConstructor  
@AllArgsConstructor  
@Setter  
@Getter  
@ToString  
public class Prototype implements PrototypeSup, Serializable {
     
 private String name;  
 private User user;
//序列化操作  
@Override  
public Object clone() {
     
    //深拷贝  

    //创建流对象        ByteArrayOutputStream bos = null;  
    ObjectOutputStream oos = null;  
    ByteArrayInputStream bis = null;  
    ObjectInputStream ois = null;  

    try {
     
        //序列化  
        bos = new ByteArrayOutputStream();  
        oos = new ObjectOutputStream(bos);  
        oos.writeObject(this); //当前这个对象以对象流的方式输出  

        //反序列化            bis = new ByteArrayInputStream(bos.toByteArray());  
        ois = new ObjectInputStream(bis);  
        Prototype prototype = (Prototype) ois.readObject();  

        return prototype
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值