设计模式(1):单例设计模式
2015-07-25 15:04
274 查看
单例设计模式:
定义:
确保一个类只有一个实例,并且自行实例化,并向整个系统提供这个实例。
饿汉式:
通过定义一个私有访问权限的构造函数,避免被其他类new出来一个对象。
懒汉式:
考虑到线程同步的问题。
单例模式的扩展:产生固定数量的对象。
定义:
确保一个类只有一个实例,并且自行实例化,并向整个系统提供这个实例。
饿汉式:
class Single { private static final Single s = new Single(); // 限制产生多个对象 private Single() { } // 通过该方法获得实例对象 public Single getInstance() { return s; } // 类中其他方法尽量使用static public static void say() { System.out.println("--> only one"); } }
通过定义一个私有访问权限的构造函数,避免被其他类new出来一个对象。
懒汉式:
考虑到线程同步的问题。
/*懒汉式 * 延迟加载 * */ class Single1 { private static Single1 s = null; private Single1() {} public static Single1 getInstance() { if ( s == null) { synchronized (Single1.class) { if (s == null) s = new Single1(); } } return s; } }
单例模式的扩展:产生固定数量的对象。
class Single { // 固定数量 private static int num = 5; private static ArrayList<String> nameList = new ArrayList<String>(); private static ArrayList<Single> singleList = new ArrayList<Single>(); private static int currentNum = 0; static { for (int i = 0; i < num; i++) { singleList.add(new Single("num + " + (i + 1))); } } private Single(String name) { nameList.add(name); } public static Single getInstance() { Random random = new Random(num); currentNum = random.nextInt(); return singleList.get(currentNum); } // 其他方法 }
相关文章推荐
- [leetcode]Word Ladder
- Android Service两种启动方式
- 维罗纳中文离线地图App上线
- 如何判断静态路由不可达 接口down ? 路由递归查找
- JavaScript中instanceof与typeof运算符的用法及区别详细解析
- SICP不是我的菜
- 使用 Markdown 写作那些事儿
- 微信学习资源
- python基础教程总结14——测试
- 牛腩新闻发布系统(6)——真假分页
- 【dfs】hdu 1111 Secret Code
- [LeetCode]3Sum
- 获取应用签名MD5指纹的方法
- windows 下安装squid3
- hdoj 2612 find a way (两次bfs)
- xml解析org.xml.sax.SAXParseException: The element type "comment" must
- shell学习笔记
- 关于hihocoder上连通分量的学习
- Code Forces 560 B. Gerald is into Art(水~)
- Hibernate 缓存机制续 - 查询缓存