一、场景
对于mybatis查询数据库。若是同一个值的多次查询,会严重损耗性能。所以在查询时加入缓存,这样在多次查询同一个值时相对会快很多。而为了避免外部对缓存中对象的修改,使用原型模式每次向外部调用返回克隆体。
无论缓存中是否存在。在缓存中放入的是本体,返回的是克隆体
二、举例
1、模拟mybatis查询数据
import java.util.HashMap;
import java.util.Map;
public class MybatisDb {
Map<String,User> userCache = new HashMap<>();
public User getUser(String userName) throws CloneNotSupportedException {
User user = null;
if(userCache.containsKey(userName)){
user = (User)userCache.get(userName).clone();
}else {
User user1 = User.builder().userName(userName).password("123").build();
userCache.put(userName,user1);
user = (User)user1.clone();
}
return user;
}
}
2、user实体
@Data
@Builder
public class User implements Cloneable{
private String userName;
private String password;
@Override
protected Object clone() throws CloneNotSupportedException {
return User.builder().userName(this.userName).password(this.password).build();
}
}
3、测试类
/**
* 要点 : 1、无论缓存中是否存在。在缓存中放入的是本体,返回的是克隆体
* @throws CloneNotSupportedException
*/
@Test
public void test1() throws CloneNotSupportedException {
MybatisDb mybatisDb = new MybatisDb();
User zhangsan = mybatisDb.getUser("张三");
System.out.println(zhangsan);
zhangsan.setPassword("11111");
System.out.println(zhangsan);
User zhangsan1 = mybatisDb.getUser("张三");
System.out.println(zhangsan1);
}