设计模式在Java中的应用:单例模式实现

原创 青旅半醒 2024-10-07 02:18 183阅读 0赞

在Java中,单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供全局访问点。

以下是使用Java实现单例模式的步骤:

  1. 饿汉式
    这种方式在类加载时就完成了初始化,无论是否需要获取实例,都可以达到线程安全的目的。
  1. public class Singleton1 {
  2. private static Singleton1 instance;
  3. private Singleton1() {}
  4. public static Singleton1 getInstance() {
  5. if (instance == null) {
  6. synchronized (Singleton1.class) {
  7. if (instance == null) {
  8. instance = new Singleton1();
  9. }
  10. }
  11. }
  12. return instance;
  13. }
  14. // 用于测试,避免单例模式导致的不便
  15. public void test() {
  16. Singleton1 instance1 = Singleton1.getInstance();
  17. Singleton1 instance2 = Singleton1.getInstance();
  18. System.out.println("instance1: " + instance1);
  19. System.out.println("instance2: " + instance2);
  20. // 如果要创建新的对象,应该使用getInstance方法
  21. // 因为Singleton1实例是在 getInstance 方法被调用时创建的
  22. // 其他任何时候调用 getInstance 方法返回的是同一个实例
  23. }
  24. }
  1. 懒汉式(在需要获取实例时才初始化):
  1. public class Singleton2 {
  2. private static Singleton2 instance;
  3. private Singleton2() {}
  4. public synchronized static Singleton2 getInstance() {
  5. if (instance == null) {
  6. instance = new Singleton2();
  7. }
  8. return instance;
  9. }
  10. // 用于测试,避免单例模式导致的不便
  11. public void test() {
  12. Singleton2 instance1 = Singleton2.getInstance();
  13. Singleton2 instance2 = Singleton2.getInstance();
  14. System.out.println("instance1: " + instance1);
  15. System.out.println("instance2: " + instance2);
  16. // 如果要创建新的对象,应该使用getInstance方法
  17. // 因为Singleton2实例是在 getInstance 方法被调用时创建的
  18. // 其他任何时候调用 getInstance 方法返回的是同一个实例
  19. }
  20. }

这两种方式都可以保证单例模式在Java中的实现。选择哪种方式主要取决于代码的需求和执行环境。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读