Java 里面实现Prototype
使用Cloneable接口
package prototype.pattern;
import java.util.Date;
/**
*
* @author Real H LI
*
*/
public class Prototype implements Cloneable {
private Date date;
private String dateStr;
private String ID;
public Prototype(){
this.date=new Date();
this.dateStr=date.toString();
setID("YYYYYYY");
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
try {
return this.getClass().newInstance();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String getDateStr() {
return dateStr;
}
public void setID(String iD) {
ID = iD;
}
public String getID() {
return ID;
}
}
package prototype.pattern;
/**
*
* @author Real H LI
*
*/
public class PrototypePattern {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Prototype prototype = new Prototype();
System.out.println(prototype.getDateStr());
System.out.println("-------------------------------");
Prototype temp;
try {
for (int i = 0; i < 10; i++) {
temp = (Prototype) prototype.clone();
System.out.println(temp.getDateStr());
temp.setID(String.valueOf(i));
}
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("-------------------------------");
System.out.println(prototype.getID());
}
}