整个应用程序中某个类只有一个对象,不会出现多个该类的对象.同时最多只有一个实例。
何时用:在开发过程中,读取配置文件时使用单态。统计在线人数时使用过单态。
Code:
资源文件:kali.properties
读取配置文件类:PropertiesRead
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesRead {
private String username;
private String password;
private static PropertiesRead pr;
public static PropertiesRead getInstanse(){
if(pr == null)
pr = new PropertiesRead();
return pr;
}
private PropertiesRead(){
System.out.println("我是读取配置文件的类。我现在实例化了。");
Properties p = new Properties();
InputStream in = PropertiesRead.class.getResourceAsStream("kali.properties");
try {
p.load(in);
this.username = p.getProperty("name");
this.password= p.getProperty("password");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class Test {
public static void main(String args[])
{
PropertiesRead pr = PropertiesRead.getInstanse();
PropertiesRead pr1 = PropertiesRead.getInstanse();
System.out.println(pr1.getUsername());
}
}