java 單例的實際應用

誰的大王發表於2015-12-26

1、 編寫單例類
public class VoteEmployeeCache {
private VoteEmployeeCache() {}
private static VoteEmployeeCache singleton = new VoteEmployeeCache();
public static VoteEmployeeCache getInstance() {
return singleton;
}
private Set<String> voteEmployeeSet = new HashSet<String>();
public void insertSet(String openId) throws Exception {
voteEmployeeSet.add(openId);
}
public Set<String> getVoteEmployeeSet() {
return voteEmployeeSet;
}
}


2、 應用
在其它方法中可以應用單例類進行處理,如下為驗證openId是否員工的微訊號
Set<String> openIdSet = VoteEmployeeCache.getInstance().getVoteEmployeeSet();
if(!openIdSet.contains(openId)){
int a=0;
List<Employee> employeeList = null;
try {
employeeList = employeeService.getEmployeeList();
} catch (NianhuiException e) {
log.error("vote---", e);
e.printStackTrace();
}
for(int i=0;i<employeeList.size();i++){
Employee employee = employeeList.get(i);
if(employee.getOpenId().equals(openId)){
openIdSet.add(openId);
a=1;
}
}
if(a==0){
jsonObject.put("voteResult", "invalid user!");
return jsonObject.toString(); //如果不是員工的微訊號則返回不執行
}
}
//如果是員工的微訊號則執行後面的流程

相關文章