原型模式就好比我们工作当中经常使用复制粘贴功能一样,把一个文件从一个地方复制到另外一个地方,复制完成之后这个文件和之前的文件也没有一点差别,这就是原型模式的思想:首先创建一个实例,然后通过这个实例去拷贝创建新的实例。
import java.util.HashMap;
import java.util.Map;
/**
* 定义一个文件,用来被复制
* @author zxs
*/
public class MyFile implements Cloneable {
private Integer fileid;
private String filename;
private Map<String, Double> scores;
public MyFile() {
super();
}
public MyFile(Integer fileid, String filename, Map<String, Double> scores) {
super();
this.fileid = fileid;
this.filename = filename;
this.scores = scores;
System.out.println("*********Prototype构造方法***********");
}
/**
* 克隆
*/
@SuppressWarnings("unchecked")
@Override
protected Object clone(){
MyFile filePrototype = null;
try {
// 有了下面这句话,基本类型就能克隆了
filePrototype = (MyFile)super.clone();
// 下面要对每一个复杂对象进行分别克隆
Object object = ((HashMap<String,Double>) this.scores).clone();
filePrototype.scores = (Map<String, Double>) object;
} catch (Exception e) {
e.printStackTrace();
}
return filePrototype;
}
public Integer getFileid() {
return fileid;
}
public void setFileid(Integer fileid) {
this.fileid = fileid;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Map<String, Double> getScores() {
return scores;
}
public void setScores(Map<String, Double> scores) {
this.scores = scores;
}
import java.util.Map;
/**
* 文件复制实现类
* @author zxs
*
*/
public class FileConcretePrototype extends MyFile {
public FileConcretePrototype(Integer fileid, String filename,Map<String, Double> scores){
super(fileid, filename, scores);
System.out.println("*********FileConcretePrototype构造方法***********");
}
/**
* 展示复制内容
*/
public void show(){
System.out.println("====文件信息=======");
System.out.println("文件名:"+this.getFilename());
System.out.println("文件号:"+this.getFileid());
System.out.println("文件打分:"+this.getScores());
}
}
/**
* 用户客户端使用复制粘贴功能
* @author zxs
*/
public class User {
public static void main(String[] args) {
String fileName = "hello";
int fileId = 1;
Map<String, Double> fileScores = new HashMap<String, Double>();
fileScores.put("语文", 79.99);
fileScores.put("英语", 89.99);
fileScores.put("数学", 99.99);
// 第一步创建出一个实例对象
FileConcretePrototype fileA = new FileConcretePrototype(fileId, fileName, fileScores);
// 第二步克隆出来几个
FileConcretePrototype fileB = (FileConcretePrototype) fileA.clone();
FileConcretePrototype fileC = (FileConcretePrototype) fileA.clone();
// 第三步:输出一下克隆出来的对象是否有变化
fileB.show();
fileC.show();
}
}