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

singleton

程序员文章站 2022-07-14 08:54:27
...

单例模式的应用场景

当你需要有且仅有一个对象,供全局使用,比如读取配置文件、数据库连接池、线程池等等

为什么要单例模式

  • 资源共享的情况下,避免由于资源操作时导致的性能或损耗等。如上述中的日志文件,应用配置。

  • 控制资源的情况下,方便资源之间的互相通信。如线程池等。

java单例模式

  • 饿汉模式
package singleton;

public class Hungry {
    private static Hungry singleton = new Hungry(); // 类加载的时候 就创建了

    private Hungry() {

    }

    public static Hungry getHungryInstance() {
        return singleton;
    }
    
}

  • 懒汉模式
package singleton;

public class Lazy {
    private Lazy() {

    }

    private static Lazy instance;

    public static Lazy getLazyInstance() {
        if (instance == null) {
            instance = new Lazy();
        }
        return instance;
    }
}

“饿汉”、“懒汉”区别

  • 类加载时,对象是否创建;饿汉加载时较慢,创建了单例对象,使用对象时很快;懒汉反之
  • 线程安全问题 饿汉是安全,懒汉不安全

网上找的一个读取配置文件的小案例

package org.jediael.util;  
  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.Properties;  
  
public class BasicConfiguration {  
  
      
    private Properties pros = null;  
      
    private static class ConfigurationHolder{  
        private static BasicConfiguration configuration = new BasicConfiguration();  
    }  
      
    public static BasicConfiguration getInstance(){  
        return ConfigurationHolder.configuration;  
    }  
      
    public String getValue(String key){  
        return pros.getProperty(key);  
    }  
      
    private BasicConfiguration(){  
        readConfig();  
    }  
      
  
  
    private void readConfig() {  
        pros = new Properties();          
        InputStream in = null;  
        try {  
            in = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("")  
                    .getPath() + "search.properties");  
            pros.load(in);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}