Java23种设计模式
原型模式就是克隆自身,是用于解决对象重复创建消耗性能的问题,或者数据的备份。
需求:我们要克隆一个细胞(母细胞)100次(取名细胞1-100),已知创造这个细胞耗时一秒钟。
1. 传统方式应该是每次new一个对象:
先创建细胞类Cell
public class Cell {
private String name;
private String age;
public Cell(String name, String age) {
try {
Thread.sleep(1000);
this.name = name;
this.age = age;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
然后创建Test类执行操作:
public class Test {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println("开始"+df.format(new Date()));// new Date()为获取当前系统时间
Cell cell = new Cell("母细胞","100岁");
List<Cell> cellList = new ArrayList<>();
cellList.add(cell);
for(int i = 0;i<100;i++){
cellList.add(new Cell("细胞"+(i+1),"100岁"));
}
System.out.println("结束"+df.format(new Date()));
}
}
耗时:1分41秒
开始2019-05-05 18:13:22
结束2019-05-05 18:15:03
2. 原型模式克隆对象:
实现Cloneable接口
public class Cell implements Cloneable{
private String name;
private String age;
public Cell(String name, String age) {
try {
Thread.sleep(1000);
this.name = name;
this.age = age;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
修改代码逻辑
public class Test {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println("开始"+df.format(new Date()));// new Date()为获取当前系统时间
Cell cell = new Cell("母细胞","100岁");
List<Cell> cellList = new ArrayList<>();
cellList.add(cell);
for(int i = 0;i<100;i++){
try {
Cell c = (Cell) cell.clone();
c.setName("细胞"+(i+1));
cellList.add(c);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
System.out.println("结束"+df.format(new Date()));
}
}
耗时:1秒
开始2019-05-05 18:23:05
结束2019-05-05 18:23:06
原理是克隆没有走构造方法,而是直接底层复制当前对象,所以原型模式适合生成重复对象或对象的备份问题。