一、定义
指原型实力制定创建对象的种类,并且通过拷贝这些原型创建新的对象。(不调用构造方法)
二、适用场景
1.类初始化消耗较多资源
2.new产生一个对象需要非常繁琐的过程
3.循环体中生产大量对象时
三、优点
简化创建过程、性能比new性能高
四、缺点
必须配备克隆方法
深拷贝、浅拷贝要运用得当
五、代码
public class Mail implements Cloneable{
private String name;
private String mailAddress;
private String content;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMailAddress() {
return mailAddress;
}
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Mail(){
System.out.println("调用构造器");
}
@Override
public String toString() {
return "Mail [content=" + content + ", mailAddress=" + mailAddress
+ ", name=" + name + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException{
System.out.println("克隆方法!");
return super.clone();
}
}
import java.text.MessageFormat;
public class MailUtil {
public static void sendMail(Mail mail){
String outputContent = "向{0}同学,邮件地址{1},邮件内容{2}";
System.out.println(MessageFormat.format(outputContent,
mail.getName(), mail.getMailAddress(), mail.getContent()));
}
public static void saveOriginMailRecord(Mail mail){
System.out.println("存储originMail记录,originMail:"+mail.getContent());
}
}