一毙芜、場(chǎng)景
對(duì)于mybatis查詢數(shù)據(jù)庫(kù)。若是同一個(gè)值的多次查詢窒朋,會(huì)嚴(yán)重?fù)p耗性能搀罢。所以在查詢時(shí)加入緩存,這樣在多次查詢同一個(gè)值時(shí)相對(duì)會(huì)快很多侥猩。而為了避免外部對(duì)緩存中對(duì)象的修改榔至,使用原型模式每次向外部調(diào)用返回克隆體。
無(wú)論緩存中是否存在欺劳。在緩存中放入的是本體唧取,返回的是克隆體
二、舉例
1划提、模擬mybatis查詢數(shù)據(jù)
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實(shí)體
@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、測(cè)試類(lèi)
/**
* 要點(diǎn) : 1鹏往、無(wú)論緩存中是否存在淡诗。在緩存中放入的是本體,返回的是克隆體
* @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);
}