Lintcode: Singleton && Summary: Synchronization and OOD
Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton. You job is to implement a getInstance method for given class, return the same instance of this class every time you call this method. Example
In Java: A a = A.getInstance();
A b = A.getInstance();
a should equal to b. Challenge
If we call getInstance concurrently, can you make sure your code could run correctly?
单例模式,这是一道OOD的题
Eager initialization
This is a design pattern where an instance of a class is created much before it is actually required. Mostly it is done on system start up. In singleton pattern, it refers to create the singleton instance irrespective of whether any other class actually asked for its instance or not.
public class EagerSingleton {
private static volatile EagerSingleton instance = new EagerSingleton(); // private constructor
private EagerSingleton() {
} public static EagerSingleton getInstance() {
return instance;
}
}
Above method works fine, but has one drawback. Instance is created irrespective of it is required in runtime or not. If this instance is not big object and you can live with it being unused, this is best approach.
Lets solve above problem in next method.
Lazy initialization
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. In singleton pattern, it restricts the creation of instance until requested first time. Lets see in code:
public final class LazySingleton {
private static volatile LazySingleton instance = null; // private constructor
private LazySingleton() {
} public static LazySingleton getInstance() {
if (instance == null) {
synchronized (LazySingleton.class) {
instance = new LazySingleton();
}
}
return instance;
}
}
On first invocation, above method will check if instance is already created using instance variable. If there is no instance i.e. instance is null, it will create an instance and will return its reference. If instance is already created, it will simply return the reference of instance.
But, this method also has its own drawbacks. Lets see how. Suppose there are two threads T1 and T2. Both comes to create instance and execute “instance==null”, now both threads have identified instance variable to null thus assume they must create an instance. They sequentially goes to synchronized block and create the instances. At the end, we have two instances in our application.
This error can be solved using double-checked locking. This principle tells us to recheck the instance variable again in synchronized block in given below way:
Double-Checking Locking: (correct version)
public class EagerSingleton {
private static volatile EagerSingleton instance = null; // private constructor
private EagerSingleton() {
} public static EagerSingleton getInstance() {
if (instance == null) {
synchronized (EagerSingleton.class) {
// Double check
if (instance == null) {
instance = new EagerSingleton();
}
}
}
return instance;
}
}
Lintcode: Singleton && Summary: Synchronization and OOD的更多相关文章
- LintCode Singleton
Singleton 3 大要素: 1.有private static的句柄(成员变量即field) 2. constructor 必须为private 3.有public static的getInst ...
- Singleton Summary
Java Singleton: Singleton pattern restricts the instantiation of a class and ensures that only one i ...
- Lintcode: Heapify && Summary: Heap
Given an integer array, heapify it into a min-heap array. For a heap array A, A[0] is the root of he ...
- C#面向对象设计模式纵横谈——2.Singleton 单件(创建型模式)
一:模式分类 从目的来看: 创建型(Creational)模式:负责对象创建. 结构型(Structural)模式:处理类与对象间的组合. 行为型(Behavioral)模式:类与对象交互中的职责分配 ...
- Net设计模式实例之单例模式( Singleton Pattern)
一.单例模式简介(Brief Introduction) 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯 ...
- 【转】单例模式(Singleton)
首先来明确一个问题,那就是在某些情况下,有些对象,我们只需要一个就可以了, 比如,一台计算机上可以连好几个打印机,但是这个计算机上的打印程序只能有一个, 这里就可以通过单例模式来避免两个打印作业同时输 ...
- 设计模式(一)单例模式(Singleton Pattern)
一.引言 最近在设计模式的一些内容,主要的参考书籍是<Head First 设计模式>,同时在学习过程中也查看了很多博客园中关于设计模式的一些文章的,在这里记录下我的一些学习笔记,一是为了 ...
- 跨应用程序域(AppDomain)的单例(Singleton)实现
转载自: 跨应用程序域(AppDomain)的单例(Singleton)实现 - CorePlex代码库 - CorePlex官方网站,Visual Studio插件,代码大全,代码仓库,代码整理,分 ...
- 设计模式:单例模式(Singleton)
定义:确保一个类仅有一个实例,并提供一个访问它的全局访问点. 优点:在内存中只有一个对象,节省了内存空间 示例: Singleton.cs 写法一:非线程安全 public class Singlet ...
随机推荐
- Python之什么是dict
我们已经知道,list 和 tuple 可以用来表示顺序集合,例如,班里同学的名字: ['Adam', 'Lisa', 'Bart'] 或者考试的成绩列表: [95, 85, 59] 但是,要根据名字 ...
- 在VC6.0中编译头文件时产生moc文件
1.在FileView视图中 右键点击需要产生moc文件的头文件(就是类中包含Q_OBJECT宏,如果没有这个宏就不需要产生moc文件) 2.在右键菜单中选择Setting... 3.选择Custom ...
- 非Controller类无法使用Service bean解决方案
尝试方案: 1 在Spring的配置文件springmvc.xml中,增加扫描项base-package="zxs.ssm.util",增加你需要使用service的类所在的包 ...
- SVN hooks强制提交时填写日志
#!/bin/bash REPOS="$1" TXN="$2" #svnlook路径 SVNLOOK=/usr/bin/svnlook #通过svnlook获取 ...
- php---分组函数group_concat()
group_concat()函数总结 group_concat(),手册上说明:该函数返回带有来自一个组的连接的非NULL值的字符串结果.比较抽象,难以理解. 通俗点理解,其实是这样的:group_c ...
- ubuntu下的jdk安装
软件环境: 虚拟机:VMware Workstation 10 操作系统:ubuntu-12.04-desktop-amd64 JAVA版本:jdk-7u55-linux-x64 软件下载地址: JD ...
- gridcontrol中使用右健菜单popupMenu1
private void gridView1_ShowGridMenu(object sender, DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs ...
- Swift 学习难点笔记
定义一个字典 let interestingNumber = [ ,,,,,], ,,,,,], ,,,,] ] var array = interestingNumber["Prime&q ...
- iOS Block传值
上个月,针对block恶补了一下,以为自己全部掌握了,其实不尽然. 昨天项目中在下载的时候用到,自己竟然不知道该从何下手,惭愧~ 情景是这个样子的:我写了个下载类,阴老师在调用时,将参数(sid,UR ...
- Selenium2学习-026-WebUI自动化实战实例-024-获取页面元素
非常简单的方法封装,就不啰嗦了,直接上码咯 ^_^ /** * Get element. It will be return null when there is not such element. ...