原型模式

简介: 《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。目录:设计模式Github地址:DesignPattern说明定义:原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。
目录:设计模式
Github地址:DesignPattern

说明

定义:原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

UML图:

img_a55c547bdf10b4f6c7ef54e8de110a60.png
原型模式UML图.png

代码实现:

原型类

我们这里使用java api中Cloneable接口

具体原型类

class ConcretePrototype1 implements Cloneable{

    private String id;
    public ConcretePrototype1(String id){
        this.id = id;
    }

    public String getId(){
        return id;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
AI 代码解读

客户端代码

public class PrototypePattern {
    public static void main(String[] args) throws CloneNotSupportedException {
        ConcretePrototype1 p1 = new ConcretePrototype1("I");
        ConcretePrototype1 c1 = (ConcretePrototype1) p1.clone();
        System.out.println("Cloned():"+c1.getId());
    }
}
AI 代码解读

运行结果

Cloned():I
AI 代码解读

示例

例子:用程序模拟写简历,要求有一个简历类,必要有姓名,可以设置性别和年龄,可以设置工作经历,最终需要三份简历。

UML图:

img_ef1ae4b3d5d2ed63a8ea47569f20c389.png
原型模式示例UML图.png

代码实现:

工作经历类

public class WorkExperence implements Serializable {
    private String workDate;
    private String company;

    public String getWorkDate() {
        return workDate;
    }

    public void setWorkDate(String workDate) {
        this.workDate = workDate;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }
}
AI 代码解读

简历类

public class Resume implements Cloneable,Serializable{
    private String name;
    private String sex;
    private int age;

    private WorkExperence workExperence;

    public Resume(){
        workExperence = new WorkExperence();
    }

    public void display() {
        System.out.println(this.getName() + " " + this.getSex() + " "
                + this.getAge() + "\n工作经历: "
                + this.getWorkExperence().getWorkDate() + " "
                + this.getWorkExperence().getCompany());
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    public WorkExperence getWorkExperence() {
        return workExperence;
    }

    public void setWorkExperence(String workDate,String company) {
        workExperence.setCompany(company);
        workExperence.setWorkDate(workDate);
    }
}
AI 代码解读

客户端调用

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
        copy();
    }

    public static void copy() throws CloneNotSupportedException {
        Resume resumeA = new Resume();
        resumeA.setName("大鸟");
        resumeA.setAge(25);
        resumeA.setSex("男");
        resumeA.setWorkExperence("2015-2016","A公司");

        Resume resumeB = (Resume) resumeA.clone();
        resumeB.setWorkExperence("2016-2017","B公司");

        Resume resumeC = (Resume) resumeA.clone();
        resumeC.setWorkExperence("2017-2018","C公司");

        resumeA.display();
        resumeB.display();
        resumeC.display();
    }
}
AI 代码解读

运行结果

大鸟 男 25
工作经历: 2017-2018 C公司
大鸟 男 25
工作经历: 2017-2018 C公司
大鸟 男 25
工作经历: 2017-2018 C公司
AI 代码解读

我们发现,设置的工作经历并没有正确的显示。原因是:如果复制的字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象,因此原始对象及其复本引用同一对象。

深拷贝实现

UML图:

img_21536bef5259076eff97de1554351b73.png
原型模式示例深拷贝UML图.png

代码实现:

简历类增加deepClone()方法

public class Resume implements Cloneable,Serializable{
    // ……
    public Object deepClone() throws IOException, ClassNotFoundException {
        // 将对象写入流内
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        // 从流内读出对象
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        return ois.readObject();
    }
}
AI 代码解读

客户端代码

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
        copy();
        
        System.out.println("==============");

        deepCopy();
    }

    public static void copy() throws CloneNotSupportedException {
        Resume resumeA = new Resume();
        resumeA.setName("大鸟");
        resumeA.setAge(25);
        resumeA.setSex("男");
        resumeA.setWorkExperence("2015-2016","A公司");

        Resume resumeB = (Resume) resumeA.clone();
        resumeB.setWorkExperence("2016-2017","B公司");

        Resume resumeC = (Resume) resumeA.clone();
        resumeC.setWorkExperence("2017-2018","C公司");

        resumeA.display();
        resumeB.display();
        resumeC.display();
    }

    public static void deepCopy() throws IOException, ClassNotFoundException {
        Resume resumeA = new Resume();
        resumeA.setName("大鸟");
        resumeA.setAge(25);
        resumeA.setSex("男");
        resumeA.setWorkExperence("2015-2016","A公司");

        Resume resumeB = (Resume) resumeA.deepClone();
        resumeB.setWorkExperence("2016-2017","B公司");

        Resume resumeC = (Resume) resumeA.deepClone();
        resumeC.setWorkExperence("2017-2018","C公司");

        resumeA.display();
        resumeB.display();
        resumeC.display();
    }
}
AI 代码解读

运行结果:

大鸟 男 25
工作经历: 2017-2018 C公司
大鸟 男 25
工作经历: 2017-2018 C公司
大鸟 男 25
工作经历: 2017-2018 C公司
==============
大鸟 男 25
工作经历: 2015-2016 A公司
大鸟 男 25
工作经历: 2016-2017 B公司
大鸟 男 25
工作经历: 2017-2018 C公司
AI 代码解读
目录
打赏
0
0
0
0
1
分享
相关文章
kde
|
7天前
|
Docker镜像加速指南:手把手教你配置国内镜像源
配置国内镜像源可大幅提升 Docker 拉取速度,解决访问 Docker Hub 缓慢问题。本文详解 Linux、Docker Desktop 配置方法,并提供测速对比与常见问题解答,附最新可用镜像源列表,助力高效开发部署。
kde
4305 10
国内如何安装和使用 Claude Code镜像教程 - Windows 用户篇
国内如何安装和使用 Claude Code镜像教程 - Windows 用户篇
715 2
Dify MCP 保姆级教程来了!
大语言模型,例如 DeepSeek,如果不能联网、不能操作外部工具,只能是聊天机器人。除了聊天没什么可做的。
1089 13
【保姆级图文详解】大模型、Spring AI编程调用大模型
【保姆级图文详解】大模型、Spring AI编程调用大模型
459 7
【保姆级图文详解】大模型、Spring AI编程调用大模型
|
4天前
typora免费版,激活方法,Typora使用教程
Typora是一款简洁高效的Markdown编辑器,支持即时渲染。本教程涵盖安装方法、文件操作、视图控制、格式排版、字体样式及Markdown语法,助你快速上手使用Typora进行高效写作。
850 0
2025年最新版最细致Maven安装与配置指南(任何版本都可以依据本文章配置)
本文详细介绍了Maven的项目管理工具特性、安装步骤和配置方法。主要内容包括: Maven概述:解释Maven作为基于POM的构建工具,具备依赖管理、构建生命周期和仓库管理等功能。 安装步骤: 从官网下载最新版本 解压到指定目录 创建本地仓库文件夹 关键配置: 修改settings.xml文件 配置阿里云和清华大学镜像仓库以加速依赖下载 设置本地仓库路径 附加说明:包含详细的配置示例和截图指导,适用于各种操作系统环境。 本文提供了完整的Maven安装和配置
2025年最新版最细致Maven安装与配置指南(任何版本都可以依据本文章配置)
【保姆级图文详解】RAG(检索增强生成)技术和流程:Embedding(语义理解) + 向量数据库(高效检索) + 召回 / 精排(筛选优化) + 混合策略(场景适配)
【保姆级图文详解】RAG(检索增强生成)技术和流程:Embedding(语义理解) + 向量数据库(高效检索) + 召回 / 精排(筛选优化) + 混合策略(场景适配)
360 5
企业如何用Data Agent实现数据价值效率的飞跃
在数字化转型背景下,数据被视为“新时代的石油”,但多数企业仍面临数据价值难以高效挖掘的困境。文章深入剖析了当前数据分析中存在的“被动响应”模式及其带来的四大挑战,并提出通过Data Agent实现主动智能与数据分析民主化的新路径。Data Agent基于大语言模型和强化学习技术,具备理解、思考与行动能力,能够从“人找数据”转变为“数据找人”,推动数据洞察从专业人员走向全员参与。
让AI时代的卓越架构触手可及,阿里云技术解决方案开放免费试用
阿里云推出基于场景的解决方案免费试用活动,新老用户均可领取100点试用点,完成部署还可再领最高100点,相当于一年可获得最高200元云资源。覆盖AI、大数据、互联网应用开发等多个领域,支持热门场景如DeepSeek部署、模型微调等,助力企业和开发者快速验证方案并上云。
356 25
让AI时代的卓越架构触手可及,阿里云技术解决方案开放免费试用
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问