欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

几种单例模式

程序员文章站 2022-07-13 23:39:56
...

1.饿汉单例模式

public class Single {
	
	public static final Single instance = new Single();
	public static Single getInstance(){
		return instance;
	}
	private Single(){
		//Single诞生时要做的事情
	}
	public void oneMethod() {
		System.out.println("I am oneMethod!");
	}
}


2.懒汉单例模式

public class Single {
	
	public static Single instance = null;
	
	public static Single getInstance(){
		if(instance == null){
			instance = new Single();
		}
		return instance;
	}
	private Single(){
		//Single诞生时要做的事情
	}
	public void oneMethod() {
		System.out.println("I am oneMethod!");
	}
}


3.静态内部类

public class Single {
	
	private static class SigletonHolder {
		private static Single instance = new Single();
	}
	public static final Single getInstance() {
		return SigletonHolder.instance;
	}
	private Single() {
		//MaYun诞生要做的事情
	}
	public void oneMethod() {
		System.out.println("I am oneMethod!");
	}
}


4.枚举单例模式

public enum Single {
	
	NumberZero(0),
    NumberOne(1),
    NumberTwo(2),
    NumberThree(3);

    private final int value;

    Single(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}


相关标签: 单例 instance