原型模式 深拷贝 反序列化方式

public abstract class SerialCloneable<T> {
    protected final T clone()  {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream bos = null;
        ObjectInputStream ois = null;
        ByteArrayInputStream bis = null;

        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(getPrototypeInstance());

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            T obj = (T) ois.readObject();
            return obj;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected abstract T getPrototypeInstance();
}
public class Citation extends SerialCloneable<Citation> implements Serializable {
    private String name;
    private Student student;

    public String getName() {
        return name;
    }

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

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    public String toString() {
        return "Citation{" +
                "name='" + name + '\'' +
                ", student=" + student +
                '}';
    }


    @Override
    protected Citation getPrototypeInstance() {
        return this;
    }
}
public class Student implements Serializable {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

 

posted on 2022-04-16 18:10  金满仓  阅读(12)  评论(0编辑  收藏  举报

导航