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(); //如果不是员工的微信号则返回不执行
}
}
//如果是员工的微信号则执行后面的流程
java 单例的实际应用
最新推荐文章于 2024-09-07 14:13:10 发布