原型模式
应用:克隆对象
- 依赖于外部资源或硬件密集型操作进行新对象的创建(对象比较复杂)
- 获取相同对象在相同拷贝状态的拷贝而无需进行重复获取状态操作的情况(不需要重新初始化,获取当前状态)
- 在不确信所属具体类时需要对象的实例情况
引出:复制三只羊
package com.fspdfcy.designmodel.prototype.improve1;
import com.alibaba.fastjson.JSON;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* @author fspdf
* @version 1.0
* @description 羊
* @date 2022/12/28
* @since designModel
*/
public class Sheep {
private String name;
private Integer age;
private String color;
private Horn horn;
public Sheep(String name, Integer age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
public Sheep() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Horn getHorn() {
return horn;
}
public void setHorn(Horn horn) {
this.horn = horn;
}
@Override
public String toString() {
return "Sheep{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
", horn=" + horn +
'}';
}
}
一般做法
Sheep sheep1 = new Sheep("tom", 12, "red");
// 复制羊1 3次
Sheep sheep2 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor());
Sheep sheep3 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor());
Sheep sheep4 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor());
System.out.println(sheep1);
System.out.println(sheep2);
System.out.println(sheep3);
缺点:
- 总是需要拿到原有的状态
- 复制比较复杂
原型模式 uml图
使用原型模式解决 uml
浅拷贝
Sheep sheep1 = new Sheep("tom", 12, "red");
sheep1.setHorn(new Horn("red"));
// 复制羊1 3次
Sheep sheep2 = sheep1.clone();
Sheep sheep3 = sheep1.clone();
Sheep sheep4 = sheep1.clone();
System.out.println(sheep1);
System.out.println(sheep2);
sheep1.getHorn().setColor("green");
System.out.println(sheep3);
System.out.println(sheep4);
结果
Sheep{name='tom', age=12, color='red', horn=Horn{color='red'}}
Sheep{name='tom', age=12, color='red', horn=Horn{color='red'}}
Sheep{name='tom', age=12, color='red', horn=Horn{color='green'}}
Sheep{name='tom', age=12, color='red', horn=Horn{color='green'}}
注意:super.clone()是浅拷贝,当拷贝对象包含对其他对象的引用时(不包含不可变对象,例如String),需要考虑拷贝的深度。