饿汉模式: 缺点不管实例化的对象有没有使用都需要占用一定的内存
private class Dog{
private static final Dog dog=new Dog();
private Dog(){}; // 构造方法私有化
public Dog getInstance(){
return dog;
}
}
懒汉模式:当需要使用到时候才进行创建。
private class Dog{
private static volatile Dog dog;
private Dog(){};
public Dog getInstance(){
if(dog==null){
synchronized(Dog.class){
if(dog==null){
dog=new Dog();
}
}
}
return dog;
}
}
解决反射破坏单例问题:
private class Dog{
private static volatile Dog dog;
private Dog(){
//如果对象不为空 则抛出异常
if (dog != null) {
throw new RuntimeException();
}
}
public Dog getInstance(){
if(dog==null){
synchronized(Dog.class){
if(dog==null){
dog=new Dog();
}
}
}
return dog;
}
}
解决序列号破坏单例问题:
private class Dog implements Serializable{
private static volatile Dog dog;
private Dog(){
//如果对象不为空 则抛出异常
if (dog != null) {
throw new RuntimeException();
}
}
public Dog getInstance(){
if(dog==null){
synchronized(Dog.class){
if(dog==null){
dog=new Dog();
}
}
}
return dog;
}
//在反序列化时会调用此方法而不需要再反序列化另一个对象
// 当JVM从内存中反序列化地"组装"一个新对象时,就会自动调用这个 readResolve方法来返回我们指定好的对象了,单例规则也就得到了保证。
private Object readResolve(){
return dog;
}
}