主要几种可以用的方法
单例模式:顾名思义就是只有一个实例,并且她自己负责创建自己的对象,这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
1. 饿汉式之静态变量写法
//单例模式之饿汉式(静态变量式写法)
/*
优点:实例在类加载的时候就实例化了,避免了同步问题
缺点:实例在类加载时实例化,可能没用到,就造成内存浪费*/
class Singleton{
private static final Singleton instance=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
public class Singleton01 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
Singleton instance1 = Singleton.getInstance();
System.out.println(instance==instance1);//truea
}
}
2. 饿汉式之静态语块写法
class Singletonstatic{
private final static Singletonstatic singleton;
static{
singleton=new Singletonstatic();
}
private Singletonstatic(){
}
public static Singletonstatic getInstance(){
return singleton;
}
}
public class Singleton02 {
public static void main(String[] args) {
Singletonstatic instance = Singletonstatic.getInstance();
Singletonstatic instance1 = Singletonstatic.getInstance();
System.out.println(instance.hashCode());
System.out.println(instance1.hashCode());
}
}
3. 懒汉式(双重检查,线程安全且保证了效率)
class Singleton03{
//加入volatile防止指令重排
private static volatile Singleton03 instance;
private Singleton03(){
}
public static Singleton03 getInstance(){
if(instance==null){
synchronized (Singleton03.class){
if(instance==null){
instance=new Singleton03();
}
}
}
return instance;
}
}
public class SingletonLazy03 {
public static void main(String[] args) {
Singleton03 instance = Singleton03.getInstance();
Singleton03 instance1 = Singleton03.getInstance();
System.out.println(instance==instance1);
}
}
4. 懒汉式(静态内部类)
class Singleton05{
private static volatile Singleton05 singleton05;
private Singleton05(){
}
//利用静态内部类可以实现懒加载,在类加载时,静态内部类不会加载
private static class Singletoninstance{
private static final Singleton05 s=new Singleton05();
}
/*当调用getInstance时,JVM虚拟机会加载上面的静态内部类
实现了线程安全,因为JVM加载类的时候是线程安全的*/
public static Singleton05 getInstance(){
return Singletoninstance.s;
}
}
public class SingletonLazy04 {
public static void main(String[] args) {
Singleton05 instance = Singleton05.getInstance();
Singleton05 instance1 = Singleton05.getInstance();
System.out.println(instance.hashCode());
System.out.println(instance1.hashCode());
}
}
6. 枚举实现单例模式(最简便,java作者推荐使用)
enum Singleton06{
INSTANCE;
public void sayok(){
System.out.println("ok");
}
}
public class SingletonLazy05 {
public static void main(String[] args) {
Singleton06 instance = Singleton06.INSTANCE;
Singleton06 instance1 = Singleton06.INSTANCE;
System.out.println(instance.hashCode());
System.out.println(instance1.hashCode());
instance.sayok();
}
}