首页 > 代码库 > java单例模式等一些程序的写法....持续更新...

java单例模式等一些程序的写法....持续更新...

一、单例模式的写法:

public class MyFactory {
    /**
     * 饿汉式
     */
    private static MyFactory instance = new MyFactory();
    
    private MyFactory(){
        
    }
    
    public static MyFactory getInstance(){
        return instance;
    }
}
public class MyFactory {
    
    /**
     * 懒汉式(要注意处理线程安全问题)
     */
    private static MyFactory instance;
    
    public static MyFactory getInstance(){
        if(instance == null){
            synchronized(MyFactory.class){
                if(instance == null){
                    instance = new MyFactory();
                }
            }
        }
        
        return instance;
    }
}

 

 

 

 

 

 

 

 

 

 

--------------

java单例模式等一些程序的写法....持续更新...