Java设计模式系列(3):原型模式

布鸽不鸽 Lv4

前言

原型模式:用已经创建的实例作为原型,通过复制该原型的值来创建一个相同的新对象

原文地址:https://xuedongyun.cn/post/12331/

浅克隆

原型模式包含以下角色:

  • 抽象原型类
  • 具体原型类
  • 访问类(调用clone方法)
classDiagram
class Prototype {
    <>
    + clone(): Prototype
}

class Realizetype {
    + clone(): Prototype
}

Prototype <|.. Realizetype

Object类中实现了一个protected修饰的naive方法clone()。我们必须实现Cloneable接口并重写clone()(其实就是调用父类方法),才能调用这个方法

1
2
3
4
5
6
7
public class User implements Cloneable {

@Override
protected User clone() throws CloneNotSupportedException {
return (User) super.clone();
}
}

深克隆

对象实现Serializable接口,使用序列化的方式存到文档中,再读出来

1
2
3
4
5
6
7
8
9
// 对象写出到文件
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c://test.txt"));
oos.writeObject(user);
oos.close();

// 从文件中写入
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c://test.txt"));
User clone = (User) ois.readObject();
ois.close();
  • 标题: Java设计模式系列(3):原型模式
  • 作者: 布鸽不鸽
  • 创建于 : 2023-06-22 10:16:30
  • 更新于 : 2023-06-23 22:01:46
  • 链接: https://xuedongyun.cn//post/12331/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
此页目录
Java设计模式系列(3):原型模式