原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节
在类中需要实现Cloneable接口,重写clone方法即可。需要注意的是深拷贝和浅拷贝问题。
浅拷贝是指实体类中对象属性,在进行拷贝的时候不会复制对象属性的属性,而是直接复制地址。因此解决办法是在对象属性中再重写clone方法
没有代码构成图,直接上代码吧!
/**
* 简历类
*/
public class Resume implements Cloneable{
/** 姓名 */
private String name;
/** 岗位 */
private String post;
/** 工作经历 */
private WorkExperience workExperience;
/**
* 重写clone方法
*/
@Override
public Resume clone(){
Resume resume = null;
try {
resume = (Resume) super.clone();
resume.workExperience = this.workExperience.clone();
}catch (CloneNotSupportedException e){
System.out.println("克隆失败");
}
return resume;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public WorkExperience getWorkExperience() {
return workExperience;
}
public void setWorkExperience(String time, String company) {
this.workExperience = new WorkExperience();
this.workExperience.setTimeArea(time);
this.workExperience.setCompany(company);
}
@Override
public String toString() {
return "Resume{" +
"name='" + name + '\'' +
", post='" + post + '\'' +
", workExperience=" + workExperience +
'}';
}
}
/**
* 工作经历类
*/
public class WorkExperience implements Cloneable{
private String timeArea;
private String company;
public WorkExperience(String timeArea, String company) {
this.timeArea = timeArea;
this.company = company;
}
public WorkExperience() {
}
@Override
public WorkExperience clone(){
WorkExperience workExperience = null;
try {
workExperience = (WorkExperience) super.clone();
}catch (CloneNotSupportedException e){
System.out.println("工作经历克隆失败");
}
return workExperience;
}
public String getTimeArea() {
return timeArea;
}
public void setTimeArea(String timeArea) {
this.timeArea = timeArea;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
public String toString() {
return "WorkExperience{" +
"timeArea='" + timeArea + '\'' +
", company='" + company + '\'' +
'}';
}
}
/**
* 测试客户端
*/
public class PrototypeDemo {
public static void main(String[] args) {
Resume resume = new Resume();
resume.setName("软软");
resume.setPost("JAVA开发工程师");
resume.setWorkExperience("2019-2020", "阿里妈妈公司");
System.out.println(resume);
Resume clone = resume.clone();
clone.setPost("软软");
clone.setPost("前端工程师");
clone.getWorkExperience().setCompany("阿里叔叔公司");
System.out.println(clone.getWorkExperience());
}
}