06-原型模式
Posted Oh,mydream!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了06-原型模式相关的知识,希望对你有一定的参考价值。
06-原型模式
概念
原型模式,不知道为啥叫这个名字,直接叫克隆模式不比原型模式顾名思义的多?
主要涉及的知识就是深拷贝和浅拷贝
浅拷贝是值直接复制拷贝。对象的话是拷贝了一份地址的值,指向的还是同一个对象
实现
package com.gof.proto;
import lombok.Data;
/**
* 功能描述
*
* @since 2023-01-19
*/
@Data
public class Resume implements Cloneable
private String name;
private String age;
private String sex;
private WorkExperience workExperience;
@Override
protected Object clone() throws CloneNotSupportedException
// 浅拷贝
// return super.clone();
// 深拷贝
Resume resume = (Resume) super.clone();
resume.setWorkExperience((WorkExperience) resume.getWorkExperience().clone());
return resume;
@Override
public String toString()
return "Resume" + "name=\'" + name + \'\\\'\' + ", age=\'" + age + \'\\\'\' + ", sex=\'" + sex + \'\\\'\'
+ ", workExperience=" + workExperience + \'\';
package com.gof.proto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 功能描述
*
* @since 2023-01-19
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WorkExperience implements Cloneable
private String datetime;
private String experience;
@Override
protected Object clone() throws CloneNotSupportedException
return super.clone();
package com.gof.proto;
/**
* 功能描述
*
* @since 2023-01-19
*/
public class Client
public static void main(String[] args) throws CloneNotSupportedException
Resume resume = new Resume();
resume.setName("dream");
resume.setAge("18");
WorkExperience experience = new WorkExperience("2023", "asdfasdf");
resume.setWorkExperience(experience);
Resume resume1 = (Resume) resume.clone();
resume.setName("dream1");
resume.setAge("19");
System.out.println(resume);
System.out.println(resume1);
System.out.println(resume.getWorkExperience() == resume1.getWorkExperience()); // 浅拷贝:true 深拷贝:false
System.out.println(resume.getWorkExperience().equals(resume1.getWorkExperience()));// 浅拷贝:true 深拷贝:true
总结
原型模式在java中实现深拷贝是通过手动在clone()方法中实现的,多层深拷贝以此类推
以上是关于06-原型模式的主要内容,如果未能解决你的问题,请参考以下文章