Java静态变量的用法:伪单例
这几天遇到一个问题,一个Service里有一个map,但是这个Service有别的继承,于是每一个Service都会创建一个map,但是这个map应该是公用的,于是就有问题了。。。(按结构说Service里是不应该有map存在的,结果设计有问题,但是结构不影响研究)
特殊的解决方式:把此map改为static即可,因为一个类的静态变量在不同实例中是共用的,所以这样便实现了map的单例模式。
(标准解决方案是放在一个单例的manager中,以便公共调用,这里偷懒。。。)
还有标准单例,一个private static的本类实例,一个public static的获取本类实例的方法,关键的在于构造方法是私有的。(没有构造时默认为共有构造,所以一定要重写构造方法)
public class RateManager { private static RateManager singleInstance = new RateManager(); public static RateManager getInstance() { return singleInstance; } private RateManager(){ BillRateService billRateService = ApplicationHelper.getApplicationContext().getBean(BillRateService.class); this.agentRateMap = billRateService.getSipuserRateMap(); this.groupRateMap = billRateService.getSkillGroupRateMap(); } private Map<String, BillRate> agentRateMap = new HashMap<>(); private Map<String, BillRate> groupRateMap = new HashMap<>(); public void addAgent(String key, BillRate rate) { this.agentRateMap.put(key, rate); } public void addGroup(String key, BillRate rate) { this.groupRateMap.put(key, rate); } public void deleteAgent(String key, BillRate rate) { this.agentRateMap.remove(key); } public void deleteGroup(String key, BillRate rate) { this.groupRateMap.remove(key); } public void refresh() { BillRateService billRateService = ApplicationHelper.getApplicationContext().getBean(BillRateService.class); this.agentRateMap = billRateService.getSipuserRateMap(); this.groupRateMap = billRateService.getSkillGroupRateMap(); } public BillRate getAgentRate(String agentName) { BillRate rate = this.agentRateMap.get(agentName); if (rate == null) rate = this.agentRateMap.get(null); return rate; } public BillRate getGroupRate(String queueId) { BillRate rate = this.groupRateMap.get(queueId); if (rate == null) rate = this.groupRateMap.get(null); return rate; } }
这样还有一个好处就是,可以在构造方法时初始化一些东西。因为静态方法是第一次调用的时候才会初始化的,所以第一次调用的时候才会走new,成功在启动后初始化。