java 单例模式

1.单例模式特点:

    (1)创建一个private的构造方法,确保外层不会实例化。

    (2)提供一个静态的最终的对象,该对象在类加载时被初始化,该对象是唯一一个该类的对象.

单例模式可简单分成两种:

   饿汉式和懒汉式。

  1.饿汉式

     public class  Singleton{
      //私有类对象

       private static Singleton singleton = new Singleton();

      //私有构造方法,不能让外类创建对象

      private Singleton(){

      }

      public static Singleton getInstall(){

            return singleton;

     }

   }

  饿汉式在类加载时就会创建一个对象,外面想要调用这个类,需要用getInstall方法,这个方法返回类加载时的对象。

 2.懒汉式

  public class  Singleton{
      //私有类对象

       private static Singleton singleton = null;

      //私有构造方法,不能让外类创建对象

      private Singleton(){

      }

      public synchronized static Singleton getInstall(){

            if(singleton == null){

              singleton = new Singleton();

           }

            return singleton;

     }

   }

 大家应该注意到了,饿汉式创建对象会在外面想要时再创建,如果没有会创建一个新的,这种模式多用于多线程。


下面我们用单例模式创建递增序列

 public class KeyInstall {
    private static KeyInstall key = new KeyInstall();
private int count = 0;
       private KeyInstall(){
}

public static KeyInstall getInstall(){
return key;
}

public synchronized int getSequence(){
return count++;
}
}

通过main函数验证:

public class KeyMain {
    private static KeyInstall key;
public static void main(String[] args) {
key = KeyInstall.getInstall();
System.out.println("key id :"+key.getSequence());
System.out.println("key id :"+key.getSequence());
System.out.println("key id :"+key.getSequence());
}

}

最后验证结果:

key id :0
key id :1
key id :2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值