【设计模式系列学习笔记】9、原型模式 prototype

原型模式prototype,用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象;

原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节;

对于java而言,就是克隆,需要实现Cloneable接口,并覆写clone方法,分为浅克隆和深克隆;

clone默认方法,如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型的,则复制引用但不复制引用的对象,所以原始对象及其复本引用同一对象;

浅克隆,被克隆的对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象;

深克隆,把引用对象的变量指向复制过的新对象,而不是原有的被引用的对象;

通过new产生一个对象需要非常繁琐的数据准备或访问权限时,则可以使用原型模式;

短时间内创建大量对象,并且new比较耗时时使用;

还可以通过序列化和反序列化实现深克隆

public static void main(String[] args) {
    Resume resume1 = new Resume("Jhon Smith");
    resume1.setPersonelInfo("female", 22);
    resume1.setWorkExperience("1998-2002", "XX Company");
    ByteArrayOutputStream bos = null;
    ObjectOutputStream oos = null;
    ByteArrayInputStream bis = null;
    ObjectInputStream ois = null;
    Resume resume2 = null;
    try {
        bos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bos);
        oos.writeObject(resume1);
        byte[] bytes = bos.toByteArray();
        bis = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(bis);
        resume2 = (Resume) ois.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(ois);
        close(bis);
        close(oos);
        close(bos);
    }
    resume1.display();
    if (null != resume2) {
        resume2.setWorkExperience("2002-2006", "YY Company");
        resume2.display();
    }
}

private static void close(InputStream is) {
    if (null != is) {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private static void close(OutputStream os) {
    if (null != os) {
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

具体代码详见

https://git.lug.ustc.edu.cn/hellboy0621/transformer_gof23.git

猜你喜欢

转载自blog.csdn.net/hellboy0621/article/details/100531616
今日推荐