我想制作一个单例类电话,以便它可以初始化(带有数字)并且是并发安全的。所以,这就是我带来的:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PhoneTest {
public static void main(String... args){
System.out.println(Phone.getInstance().getNumber());
}
static final class Phone {
private final String number;
private final static Phone instance;
static {
instance = new Phone(PhonePropertyReader.readPhoneNumber());
}
private Phone(String number) {
this.number = number;
}
public static Phone getInstance() {
if (instance == null) throw
new IllegalStateException("instance was not initialized");
return instance;
}
public String getNumber() {
return number;
}
}
static final class PhonePropertyReader {
static String readPhoneNumber() {
File file = new File("phone.properties");
String phone = "";
System.out.println(file.getAbsolutePath());
if (!file.exists()) {
return phone = "555-0-101";
}
try {
BufferedReader r = new BufferedReader(new FileReader(file));
phone = r.readLine().split("=")[1].trim();
r.close();
} catch (IOException e) {
}
return phone;
}
}
}
我还有一个文件 phone.properties 包含
phone=12345
这是一个很好的解决方案吗?并发安全吗?