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 ...
随机推荐
- a single statement, not multiple statements
http://dev.mysql.com/doc/refman/5.7/en/prepare.html Statement names are not case sensitive. preparab ...
- 3D 生物打印血管成功植入恒河猴体内
3D 生物打印血管成功植入恒河猴体内
- [troubleshoot][archlinux][X] plasma(KDE) 窗口滚动刷新冻结(约延迟10s)(已解决,root cause不明,无法再次复现)
现象: konsole,setting等plasma的系统应用反应缓慢,在滚动条滚动时,尤为明显. 触发条件: 并不是十分明确的系统滚动升级(Syu)后,产生. 现象收集: 可疑的dmesg [ :: ...
- java 开发, jdk 1.6 官方下载地址
在oracle官方网站默认下载的jdk是最新的,目前正式版是1.8. 但有些项目要求是1.6的jdk,费了九牛二虎之力终于找到了1.6的官方版本,链接如下: http://www.oracle.com ...
- php--validate表单验证实例
验证效果:
- "rel=nofollow"属性简介
nofollow是HTML元标签(meta)的content属性和链接标签(a)的rel属性的一个值,告诉机器(爬虫)无需追踪目标页,为了对抗blogspam(博客垃圾留言信息),Google推荐使用 ...
- javascript 模式方面的学习
看了好多网上的文章,基本上得到一个结论:一些写类工具函数或框架的写类方式本质上都是 构造函数+原型 1.用构造函数来定义类属性(字段).2.用原型方式来定义类的方法. 具体文章请参阅 JavaScri ...
- The Top Five Software Project Risks
Risk management (or more precisely risk avoidance) is a critical topic, but one that is often dull t ...
- C# serialport
最近使用C#写串口的程序,实现串口助手的功能,参考文档记录于此. 参考文档 http://blog.csdn.net/geekwangminli/article/details/7851673 htt ...
- SQL判断字符串里不包含字母
Oracle: 方法一:通过To_Number 函数异常来判断,因为这个函数在转换不成功的时候是报错,所以只能用存储过程包装起来. CREATE OR REPLACE FUNCTION Is_Numb ...