implement singleton

Two way to implement singleton pattern

posted Sep 12, 2011, 1:35 PM by Akrem AYADI   [ updated Sep 12, 2011, 2:00 PM ]

You find bellow the two ways to implement singleton pattern:

 

Classic implementation

To implement singleton pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor

public class SingletonClass {

      // Note that the constructor is private

      private SingletonClass() {

            // Optional Code

      }

}

 

 

Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonClass {

 

            private static SingletonClass instance;

            // Note that the constructor is private

            private SingletonClass() {

                  // Optional Code

            }

            public static synchronized SingletonClass getInstance() {

                  if (instance == null) {

                        instance = new SingletonClass();

                  }

                  return instance;

            }

}

 

 

Step 3: Make the Access method Synchronized to prevent Thread Problems.

public static synchronized SingletonClass getInstance() {

                  if (instance == null) {

                        instance = new SingletonClass();

                  }

                  return instance;

            }

 

 

Step 4: Override the Object clone method to prevent cloning.

            @Override

            public Object clone() throwsCloneNotSupportedException {

                  throw new CloneNotSupportedException();

            }

 

 

 

New implementation

The new implementation is easier than the first. We will just make the instance variable as private static final and update getInstance() method. 
This is the new class implementation:

public class SingletonClass {

 

            private static final SingletonClass instance = newSingletonClass();

            // Note that the constructor is private

            private SingletonClass() {

                  // Optional Code

            }

            public static SingletonClass getInstance() {

                 

                  return instance;

            }

            @Override

            public Object clone() throwsCloneNotSupportedException {

                  throw new CloneNotSupportedException();

            }

}

 

 

For performance reason, I advise you to use the new implementation J

转载于:https://www.cnblogs.com/leetcode/p/3308321.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值