原型模式(serializable接口实现深复制)


原型模式

 

可以使用serializable接口实现对象的深复制

 

**************************************************

相关接口

 

Serializable

public interface Serializable {
}

说明:该接口为标识接口,表明实现该接口的类可被序列化

 

 

***************************************************

示例

 

class Address implements Serializable {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

}

class Person implements Cloneable,Serializable{

    private String name;
    private Integer age;
    private Address address;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return this.name+"  "+this.age+"  "+this.address+"  "+super.toString();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object object=null;
        try{
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(this);

            ByteArrayInputStream inputStream=new ByteArrayInputStream(outputStream.toByteArray());
            ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);

            object=objectInputStream.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }

        return object;
    }
}

public class MyTest {

    public static void main(String[] args) throws Exception{
        Address address=new Address();
        address.setId(1);
        address.setName("新世界");

        Person person=new Person();
        person.setName("瓜田李下");
        person.setAge(24);
        person.setAddress(address);
        System.out.println(person);

        Person person2=(Person)person.clone();
        System.out.println(person2);
    }
}

 

******************************************

控制台输出

 

瓜田李下  24  hello5.Address@49097b5d  hello5.Person@2f4d3709
瓜田李下  24  hello5.Address@2b05039f  hello5.Person@3d82c5f3

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值