定义与类型
- 定义:原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
- 不需要知道任何创建的细节,不调用构造函数
- 类型:创建型
适用场景
- 类初始化消耗较多资源
- new产生的一个对象需要非常繁琐的过程(数据准备、访问权限等)
- 构造函数比较复杂
- 循环体中生产大量对象
优点
- 原型模式性能比直接new一个对象性能高
- 简化创建过程
缺点
- 必须配备克隆方法
- 对克隆复杂对象或对克隆出的对象进行复杂改造时,容易引入风险
- 深拷贝、浅拷贝要运用得当
代码演示
给一个邮件模板,发送给不同的人,并保存原始邮件
- 创建Mail类
/**
* @author lijiayin
*/
public class Mail implements Cloneable{
private String name;
private String emailAddress;
private String content;
public Mail(){
System.out.println("Mail Class Constructor");
}
@Override
protected Object clone() throws CloneNotSupportedException {
System.out.println("clone mail object");
return super.clone();
}
@Override
public String toString() {
return "Mail{" +
"name='" + name + '\'' +
", emailAddress='" + emailAddress + '\'' +
", content='" + content + '\'' +
'}' + super.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
- 创建MailUtil类
import java.text.MessageFormat;
/**
* @author lijiayin
*/
public class MailUtil {
public static void sendMail(Mail mail){
String outputContent = "向{0}同学,邮件地址:{1},邮件内容:{2},发送邮件成功!";
System.out.println(MessageFormat.format(outputContent, mail.getName(),
mail.getEmailAddress(), mail.getContent()));
}
public static void saveOriginMailRecord(Mail mail){
System.out.println("存储原始邮件记录,原始邮件为:" + mail);
}
}
- 创建测试类
/**
* @author lijiayin
*/
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
//假设mail创建非常复杂
Mail mail = new Mail();
mail.setContent("恭喜你中奖了!");
System.out.println("原始邮件:" + mail);
for (int i = 0; i < 10; i++) {
Mail mailTemp = (Mail) mail.clone();
mailTemp.setName("姓名" + i);
mailTemp.setEmailAddress("姓名" + i +"@foxmail.com");
MailUtil.sendMail(mailTemp);
System.out.println("复制的邮件:" + mailTemp);
}
MailUtil.saveOriginMailRecord(mail);
}
}
-
测试结果
- 结论
实现了把一个模板对象,复制成多个不同的对象,并修改各的自属性,最终模板对象保持不变。
原型模式的另一种用法——继承
- 代码如下
/**
* @author lijiayin
*/
public abstract class A implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/**
* @author lijiayin
*/
public class B extends A {
public static void main(String[] args) throws CloneNotSupportedException {
B b = new B();
System.out.println(b);
B clone = (B) b.clone();
System.out.println(clone);
}
}
-
运行结果
深克隆与浅克隆
浅克隆
- 创建Pig类
import java.util.Date;
/**
* @author lijiayin
*/
public class Pig implements Cloneable {
private String name;
private Date birthday;
public Pig(String name, Date birthday){
this.name = name;
this.birthday = birthday;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Pig{" +
"name='" + name + '\'' +
", birthday=" + birthday +
'}' + super.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
- 创建测试类
import java.util.Date;
/**
* @author lijiayin
*/
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Date birthday = new Date(0L);
Pig pig1 = new Pig("佩奇", birthday);
Pig pig2 = (Pig) pig1.clone();
System.out.println(pig1);
System.out.println(pig2);
pig1.getBirthday().setTime(666666666666L);
System.out.println(pig1);
System.out.println(pig2);
}
}
-
测试结果
- 结论
birthday被修改后,两个对象的值都发生了改变;因此Date属性没有被克隆,仍然是同一个;是浅克隆。
深克隆
- 修改Pig类
import java.util.Date;
/**
* @author lijiayin
*/
public class Pig implements Cloneable {
private String name;
private Date birthday;
public Pig(String name, Date birthday){
this.name = name;
this.birthday = birthday;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Pig pig = (Pig) super.clone();
//深克隆
pig.birthday = (Date) pig.getBirthday().clone();
return pig;
}
@Override
public String toString() {
return "Pig{" +
"name='" + name + '\'' +
", birthday=" + birthday +
'}' + super.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
-
测试结果
- 结论
Date也被克隆了,是深克隆。
克隆破坏单例模式
代码演示
- 修改之前HungrySingleton类,使其实现Cloneable接口
import java.io.Serializable;
/**
* @author lijiayin
*/
public class HungrySingleton implements Serializable,Cloneable {
private final static HungrySingleton hungrySingleton;
static {
hungrySingleton = new HungrySingleton();
}
private HungrySingleton(){
if(hungrySingleton != null){
throw new RuntimeException("单例构造器禁止反射调用");
}
}
public static HungrySingleton getInstance(){
return hungrySingleton;
}
private Object readResolve(){
return hungrySingleton;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
- 创建测试类
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author lijiayin
*/
public class SingletonTest {
public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
HungrySingleton hungrySingleton = HungrySingleton.getInstance();
Method method = hungrySingleton.getClass().getDeclaredMethod("clone");
HungrySingleton cloneHungrySingleton = (HungrySingleton) method.invoke(hungrySingleton);
System.out.println(hungrySingleton);
System.out.println(cloneHungrySingleton);
}
}
-
测试结果
如何解决
- 不实现Cloneable接口
- 重写clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
return getInstance();
}
框架源码示例
- ArrayList:实现了Cloneable接口,重写了clone方法
public Object clone() {
try {
ArrayList> v = (ArrayList>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
- HashMap:实现了Cloneable接口,重写了clone方法
public Object clone() {
HashMap result;
try {
result = (HashMap)super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
result.reinitialize();
result.putMapEntries(this, false);
return result;
}