单例模式有两种常见的实现方式:饿汉式和懒汉式。

在饿汉式单例模式中,实例在类加载时就被创建,并且在整个应用程序的生命周期中都存在。饿汉式单例模式的实现比较简单,但需要注意的是,如果实例化的过程比较耗时或占用过多的内存,可能会对应用程序的性能产生影响。

以下是饿汉模式下单例的实现:

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

在懒汉式单例模式中,实例在第一次使用时才被创建。这种实现方式可以延迟实例化,从而减少内存占用和提高性能。但需要注意的是,如果多个线程同时访问 getInstance() 方法,可能会创建多个实例,因此需要使用线程安全的技术来保证单例性(synchronized )

以下是一个简单的懒汉式单例模式的示例代码:

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

 

posted on 2023-07-17 16:31  square凉  阅读(16)  评论(0)    收藏  举报