(文章翻译自Java Design Pattern: Singleton

单例是在Java最经常被用到的设计模式。它通过阻止其他的实例化和修改来用于控制创建对象的数目。这一特性可应用于那些当只有一个对象存在时能够更加有效的系统,或者是限制对象的实例化数目,比如:

1.私有化构造器(private constructor -)-没有其他的类可以实现化一个新的对象

2.私有化引用(private reference -)-没有其他的修改

3.公共的静态方法(public static method):仅有的获取一个对象的途径

单例的举例

这是一个简单的应用场景。一个国家只会有一个总统。所以任何时候一个总统总是被需要的,唯一的总统应该是返回而不是创建一个新的。getPresident()方法将会确保只有有一个总统被创建。

类图和代码

饿汉模式代码:

public class AmericaPresident {
private static final AmericaPresident thePresident = new AmericaPresident(); private AmericaPresident() {} public static AmericaPresident getPresident() {
return thePresident;
}
}

thePresident 被声明为final,所以它只会有一个引用。

懒汉模式:

public class AmericaPresident {
private static AmericaPresident thePresident; private AmericaPresident() {} public static AmericaPresident getPresident() {
if (thePresident == null) {
thePresident = new AmericaPresident();
}
return thePresident;
}
}

单例模式在Java标准库中的应用

java.lang.Runtime#getRuntime() 是Java标准库中最频繁被用到的方法。getRunTime()方法返回了和当前Java应用程序相关的runtime 对象。

class Runtime {
private static Runtime currentRuntime = new Runtime(); public static Runtime getRuntime() {
return currentRuntime;
} private Runtime() {} //...
}

下面是一个实用getRunTime()简单的简单例子,它在一个window系统中读取一个网页。

Process p = Runtime.getRuntime().exec(
"C:/windows/system32/ping.exe programcreek.com");
//get process input stream and put it to buffered reader
BufferedReader input = new BufferedReader(new InputStreamReader(
p.getInputStream())); String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
} input.close();

输出:

Pinging programcreek.com [198.71.49.96] with 32 bytes of data:
Reply from 198.71.49.96: bytes=32 time=53ms TTL=47
Reply from 198.71.49.96: bytes=32 time=53ms TTL=47
Reply from 198.71.49.96: bytes=32 time=52ms TTL=47
Reply from 198.71.49.96: bytes=32 time=53ms TTL=47 Ping statistics for 198.71.49.96:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 52ms, Maximum = 53ms, Average = 52ms

其他的单例模式的实现

由于私有的构造函数并不能阻止通过反射的方式进行实例化对象。Joshua Bloch (Effective Java) 提供了一个关于单例的更好的实现,如果你Mnum 不太熟悉的话,下面就是一个来自于Oracle的不错的例子。

public enum AmericaPresident{
INSTANCE; public static void doSomething(){
//do something
}
}

[译]Java 设计模式之单例的更多相关文章

  1. Java设计模式之单例

    一.Java中的单例: 特点: ① 单例类只有一个实例 ② 单例类必须自己创建自己唯一实例 ③ 单例类必须给所有其他对象提供这一实例 二.两种模式: ①懒汉式单例<线程不安全> 在类加载时 ...

  2. java设计模式之单例设计模式

    单例设计模式 保证一个类在使用过程中,只有一个实例.优势就是他的作用,这个类永远只有一个实例. 优势:这个类永远只有一个实例,占用内存少,有利于Java垃圾回收. 单例设计模式关键点 私有的构造方法. ...

  3. Java设计模式之 — 单例(Singleton)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/8860649 写软件的时候经常需要用到打印日志功能,可以帮助你调试和定位问题,项目上 ...

  4. java设计模式_单例

    public class Singleton { public static void main(String[] args) throws Exception { System.out.printl ...

  5. JAVA设计模式:单例设计

    1.单例设计Singleton的引出 单例设计,从名字上首先可以看出单---即只有一个,例---只的是实例化对象:那么单例也就是说一个类,只产生了一个实例化对象.但是我们都知道,一个类要产生实例化对象 ...

  6. java设计模式之单例设计模式和多例设计模式

    单例设计模式:构造方法私有化,在类的内部定义static属性和方法,利用static方法来取得本类的实例化对象:无论外部产生多少个实例化对象,本质上只有一个实例化对象 饿汉式单例设计 class Si ...

  7. Java设计模式之单例设计模式 入门实例

    一.基础概念 (1).单例设计模式:保证一个类在内存中的对象唯一性. (2).应用场景:数据都存储在配置文件的对象中,多个程序对同一个配置文件的对象进行操作.一个程序要基于另一个程序操作后的结果进行操 ...

  8. Java设计模式之单例设计模式总结

    package singleton; /**单例设计模式 饿汉式 * * @author gx *这种方式基于classloder机制避免了多线程的同步问题,不过,instance在类装载时就实例化, ...

  9. java设计模式--解决单例设计模式中懒汉式线程安全问题

    首先写个单例,懒汉模式: public class SingleDemo { private static SingleDemo s = null; private SingleDemo(){} pu ...

随机推荐

  1. Oracle 11g oracle客户端(32位)PL/SQL develepment的安装配置

    Oracle 11g+oracle客户端(32位)+PL/SQL develepment的安装配置 之前一直想学Oracle,可是就是安装配置Oracle一直未成功,让人很苦恼,特别是什么监听器什么的 ...

  2. Cocos2dx 3.0 交流篇

    创建项目: For(MAC) Runtime Requirements Android 2.3 or newer iOS 5.0 or newer OS X 10.7 or newer Windows ...

  3. zoj 3829 Known Notation(2014在牡丹江区域赛k称号)

    Known Notation Time Limit: 2 Seconds      Memory Limit: 131072 KB Do you know reverse Polish notatio ...

  4. Codeforces 448 D. Multiplication Table

    二分法判断答案 D. Multiplication Table time limit per test 1 second memory limit per test 256 megabytes inp ...

  5. STUN协议简介

    STUN简要 STUN(Simple Traversal of UDP over NATs,NAT 的UDP简单穿越)是一种网络协议.它同意位于NAT(或多重NAT)后的client找出自己的公网地址 ...

  6. div元素上下左右居中

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  7. 【分享】小工具大智慧之Sql执行工具

    原文:[分享]小工具大智慧之Sql执行工具 工具概况 情况是这样的,以前我们公司有很多Sql用于完成一些很不起眼但又不得不完成的业务,出于方便就直接在Sql查询分析器里执行,按理说应该写一些专门的工具 ...

  8. spring data jpa使用懒操作

    如果model对象的某属性使用lazy load,调用这个属性时会报错, failed to lazily initialize a collection of role could not init ...

  9. Java实现顺序表

    利用顺序存储结构表示的顺序表称为顺序表. 它用一组连续的地址存储单元一次存放线性表中的数据元素. 顺序表的实现是数据结构中最简单的一种. 由于代码中已经有详细注释,代码外不再阐述. 下次再陈上关于顺序 ...

  10. linux_解压缩详解

    .tar 解包:tar xvf FileName.tar打包:tar cvf FileName.tar DirName(注:tar是打包,不是压缩!)———————————————.gz解压1:gun ...