设计模式:单例模式

来源:互联网 发布:c语言中的float 编辑:程序博客网 时间:2024/06/13 12:16

作为对象的创建模式,单例模式确保一个类只有一个实例,且自行实例化并向系统提供这个实例。这个类称为单例类。

单例模式的特点

  1. 单例类只能有一个实例
  2. 必须自己创建自己的唯一实例
  3. 单例类必须给其他对象提供这一实例

饿汉子式单例类

public class EagerSingleton{    private static final EagerSingleton instance = new EagerSingleton();    private EagerSingleton(){}    public static EagerSingleton getInstance(){        return instance;    }}

懒汉子式单例类

public class LazySingleton{    private static  LazySingleton instance;    private LazySingleton(){}    public static synchronized LazySingleton getInstance(){        if(null == instance){            instance = new LazySingleton();        }        return instance;    }}

Java语言中的单例模式

Java的Runtime对象:在每一个应用程序里面,都有唯一的一个Runtime对象,应用程序可以与其运行环境相互作用。Runtime类提供了一个静态工厂方法:

public static Runtime getRuntime();

Runtime对象用途:执行外部命令;返回内存;运行垃圾收集器;加载动态库。如:

这里写图片描述

上面的程序可以打开notepad程序。

优点

在内存中只有一个对象,节省内存空间。避免频繁的创建销毁对象,可以提高性能。避免对共享资源的多重占用。可以全局访问。

1 0