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
}
}
标签:06,String,Resume,clone,resume,模式,原型,private,拷贝
From: https://www.cnblogs.com/Oh-mydream/p/17061076.html