java 单例的实际应用

1、 编写单例类
public class VoteEmployeeCache {
private VoteEmployeeCache() {}
private static VoteEmployeeCache singleton = new VoteEmployeeCache();
public static VoteEmployeeCache getInstance() {
return singleton;
}
private Set voteEmployeeSet = new HashSet();
public void insertSet(String openId) throws Exception {
voteEmployeeSet.add(openId);
}
public Set getVoteEmployeeSet() {
return voteEmployeeSet;
}
}


2、 应用
在其它方法中可以应用单例类进行处理,如下为验证openId是否员工的微信号
Set openIdSet = VoteEmployeeCache.getInstance().getVoteEmployeeSet();
if(!openIdSet.contains(openId)){
int a=0;
List employeeList = null;
try {
employeeList = employeeService.getEmployeeList();
} catch (NianhuiException e) {
log.error("vote---", e);
e.printStackTrace();
}
for(int i=0;iEmployee 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(); //如果不是员工的微信号则返回不执行
}
}
//如果是员工的微信号则执行后面的流程

你可能感兴趣的:(java技术,单例,单例)