设计模式之单例模式
程序员文章站
2022-05-11 17:19:54
...
1. 单例模式是一种创建模式,用来创建类的单个实例。
单例模式的实现一般有以下规则:
a. 私有化构造方法
b. 类持有对自身的引用
c. 通过一个静态方法向外界提供这个实例
2. 直接创建方式
public class Manager { private static final Manager mgr = new Manager(); private Manager(){} public static Manager getInstance() { return mgr; } }
3. 延迟创建方式
public class Manager { private static Manager mgr = null; private Manager(){} public synchronized static Manager getInstance() { if (mgr == null) { mgr = new Manager(); } return mgr; } }
4. 检查多次获取的对象是否相同
public static void main(String[] args) { Manager mgr1 = Manager.getInstance(); Manager mgr2 = Manager.getInstance(); if (mgr1 == mgr2) { System.out.println("mgr1==mgr2"); } else { System.out.println("mgr1!=mgr2"); } }
5. 源码实例
public final class Token { public static final String TOKEN_KEY = "com.os.util.TOKEN"; private int incNumber = 0; private static Token token = null; public static Token getInstance() { if (token == null) { token = new Token(); } return token; } public synchronized String generate() { if (this.incNumber >= 1000000) { this.incNumber = 0; } else { this.incNumber += 1; } return MD5.encrypt(new Date().toString(), String.valueOf(this.incNumber)); } public synchronized void saveToken(HttpServletRequest request) { saveToken(request, generate()); } public synchronized void removeToken(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute("com.os.util.TOKEN"); } public synchronized void saveToken(HttpServletRequest request, String token) { HttpSession session = request.getSession(false); if (session == null) { return; } session.setAttribute("com.os.util.TOKEN", token); } }
上一篇: REDIS使用指南三:Redis的使用