单例模式

来源:互联网 发布:陌陌站街用什么软件 编辑:程序博客网 时间:2024/06/16 07:48

单例模式

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。在很多操作中,比如建立目录 数据库连接都需要这样的单线程操作。一些资源管理器常常设计成单例模式。
Java单例模式确保一个类只有一个实例,自行提供这个实例并向整个系统提供这个实例。
优点:1、避免实例的重复创建;
      2、避免存在多个实例引起程序逻辑思维错误;
      3、较节约内存。
单例模式分为懒汉式和饿汉式。
/** * @author Lee *@category 单例模式 懒汉式 */public class Singleton {private static Singleton uniqueInstance= null;private Singleton(){}public static Singleton getIntance(){if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;}// other method...}

/** * @author Lee *@category 单例模式 饿汉式 */class Single{private static Single onlyone = new Single();private String name;private Single(){}public static Single getSingle(){return onlyone;}}public class TestSingle {public static void main(String[] args) {Single s1 = Single.getSingle();Single s2 = Single.getSingle();if (s1 == s2) {System.out.println("s1 is equals to s2!");}}}


1 0
原创粉丝点击