通过synchronized来实现
- synchronized加在方法上
- synchronized加在代码块上
public class MyObjectBySynchronized {
private static MyObjectBySynchronized instance1;
private static MyObjectBySynchronized instance2;
/**
* 锁整个方法实现单例
* @return
*/
public synchronized static MyObjectBySynchronized getInstance1() {
if(instance1 == null) {
instance1 = new MyObjectBySynchronized();
}
return instance1;
}
/**
* 通过锁代码块+DCL双锁检锁机制实现懒汉模式单例
* @return
*/
public static MyObjectBySynchronized getInstance2() {
if(instance2 == null) {
synchronized (MyObjectBySynchronized.class) {
if(instance2 == null) {
instance2 = new MyObjectBySynchronized();
}
}
}
return instance2;
}
}
通过静态属性实现
public class MyObjectByStaticProperty {
private static MyObjectByStaticProperty instance = new MyObjectByStaticProperty();
public static MyObjectByStaticProperty getInstance() {
return instance;
}
}
通过静态代码块实现
public class MyObjectBystaticBlock {
private static MyObjectBystaticBlock instance;
static {
instance = new MyObjectBystaticBlock();
}
public static MyObjectBystaticBlock getInstance() {
return instance;
}
}
利用枚举类的构造函数,在使用枚举类会自动调用来实现
public enum MyObjectSingleton {
myObjectFactory;
MyObject myObject;
private MyObjectSingleton() {
System.out.println("Enum类的构造函数在使用枚举时会自动调用,利用此方法来实现单例");
myObject = new MyObject();//创建要实现单例的对象
}
/**
* 获取对象
* @return
*/
public static MyObject getMyObject() {
return myObjectFactory.myObject;
}
}
通过内部静态类来实现
public class MyObject implements Serializable {
private static final long serialVersionUID = 199079165697837232L;
private static class MyObjectHandler{
private static MyObject myObject = new MyObject();
}
private MyObject() {
System.out.println("MyObject init ...");
}
public static MyObject getInstance() {
return MyObjectHandler.myObject;
}
/**
* 对于支持序列化的单例,为保证反序列化时为单例,需要此方法
* @return
* @throws ObjectStreamException
*/
protected Object readResolve() throws ObjectStreamException{
System.out.println("调用了 readResolve方法!!");
return MyObjectHandler.myObject;
}
}