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的更多相关文章

  1. LintCode Singleton

    Singleton 3 大要素: 1.有private static的句柄(成员变量即field) 2. constructor 必须为private 3.有public static的getInst ...

  2. Singleton Summary

    Java Singleton: Singleton pattern restricts the instantiation of a class and ensures that only one i ...

  3. 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 ...

  4. C#面向对象设计模式纵横谈——2.Singleton 单件(创建型模式)

    一:模式分类 从目的来看: 创建型(Creational)模式:负责对象创建. 结构型(Structural)模式:处理类与对象间的组合. 行为型(Behavioral)模式:类与对象交互中的职责分配 ...

  5. Net设计模式实例之单例模式( Singleton Pattern)

    一.单例模式简介(Brief Introduction) 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯 ...

  6. 【转】单例模式(Singleton)

    首先来明确一个问题,那就是在某些情况下,有些对象,我们只需要一个就可以了, 比如,一台计算机上可以连好几个打印机,但是这个计算机上的打印程序只能有一个, 这里就可以通过单例模式来避免两个打印作业同时输 ...

  7. 设计模式(一)单例模式(Singleton Pattern)

    一.引言 最近在设计模式的一些内容,主要的参考书籍是<Head First 设计模式>,同时在学习过程中也查看了很多博客园中关于设计模式的一些文章的,在这里记录下我的一些学习笔记,一是为了 ...

  8. 跨应用程序域(AppDomain)的单例(Singleton)实现

    转载自: 跨应用程序域(AppDomain)的单例(Singleton)实现 - CorePlex代码库 - CorePlex官方网站,Visual Studio插件,代码大全,代码仓库,代码整理,分 ...

  9. 设计模式:单例模式(Singleton)

    定义:确保一个类仅有一个实例,并提供一个访问它的全局访问点. 优点:在内存中只有一个对象,节省了内存空间 示例: Singleton.cs 写法一:非线程安全 public class Singlet ...

随机推荐

  1. Connection Management and Security

    High Performance My SQL  THIRD EDITION Each client connection gets its own thread within the server ...

  2. Apache Kafka源码分析 - PartitionStateMachine

    startup 在onControllerFailover中被调用, initializePartitionState private def initializePartitionState() { ...

  3. [have_fun] 好玩哒小游戏

    好玩哒,打字小游戏:http://zty.pe/ 可好玩了,一起来玩吧!

  4. html之内联元素与块状元素;

    html之内联元素与块状元素 一.html之内联元素与块状元素 1.块状元素一般比较霸道,它排斥与其他元素位于同一行内.比如div,并且width与height对它起作用. 2.内联元素只能容纳文本或 ...

  5. ASP.NET WebForm与ASP.NET MVC的不同点

    ASP.NET WebForm ASP.NET MVC ASP.NET Web Form 遵循传统的事件驱动开发模型 ASP.NET MVC是轻量级的遵循MVC模式的请求处理响应的基本开发模型 ASP ...

  6. 【C51】单片机芯片之——图解74HC595

    第一部部分用于快速查阅使用,详细的使用见文章第二部分 引脚图

  7. 简单CMakeLists.txt文件

    #CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(server) #添加包含目录 include_directories(./in ...

  8. 根据IP查主机名和MAC地址

    根据IP查主机名: nbtstat -a XXX.XXX.XXX.XXX根据IP查MAC地址: arp -a XXX.XXX.XXX.XXXXXX.XXX.XXX.XXX指代要查的主机的IP

  9. Marriage Match IV---hdu3416(spfa + Dinic)

    题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=3416 有一个有向图,n个点,m条边,给一个起点和终点,求出从起点到终点的最短路共有几条,每 ...

  10. 使用Aspose.Cell控件实现Excel高难度报表的生成(一)

    时光飞逝,生活.工作.业余研究总是在不停忙碌着,转眼快到月底,该月的博客文章任务未完,停顿回忆一下,总结一些经验以及好的东西出来,大家一起分享一下.本文章主要介绍报表的生成,基于Aspose.Cell ...