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. LVS的DR模式配置

    一.基本规划负载均衡调度器    192.168.1.104    默认网关    192.168.1.1    ip别名    192.168.1.233realserver1    192.168 ...

  2. 初始Spring

    Spring框架概述 1.什么是Spring struts2----是web层框架,围绕请求和响应 Hibernate----是持久层框架,围绕业务的增删改查 Spring是分层的JavaSE/EE ...

  3. StringUtil

    package per.son.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.js ...

  4. osgi 命令

    安装命令 install reference:file:D:/workspace/workspace-osgi/MsgBoxCreateModule 根据 返回的 ID再运行start

  5. IE6/7中setAttribute不支持class/for/rowspan/colspan等属性

    如设置class属性 ? 1 el.setAttribute('class', 'abc'); 在IE6/7中样式“abc”将没有起作用,虽然使用el.getAttribute('class')能取到 ...

  6. phpcms 导航栏点击栏目颜色定位方法

    另:一个栏目下面如果没有子栏目,那么它调用的模板就是列表页模板(及list_为前缀的模板):如果一个栏目下面有子栏目,那么它调用的就是栏目首页模板(category_为前缀的模板). 当你这个栏目添加 ...

  7. 更强大的trim功能,过滤汉字等

    第一种方法:通过php自带的函数 <?php /* trim 去除一个字符串两端空格, rtrim 是去除一个字符串右部空格, ltrim 是去除一个字符串左部空格. */ ?> < ...

  8. HIVE中的HQL操作

    1.字段查询 select empno,ename from emp; 2.过滤where,limit,distinct select * from emp where sal >2500; s ...

  9. java的Random

    首先,Point类 public class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } bool ...

  10. 几个简单的html+css+js题目

    1.页面中有一图片,请在下划线处添加代码能够实现隐藏该图片的功能 <img id="pic" src="door.jpg" width="200 ...