1

我想制作一个单例类电话,以便它可以初始化(带有数字)并且是并发安全的。所以,这就是我带来的:

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

这是一个很好的解决方案吗?并发安全吗?

4

2 回答 2

1

我相信Enum仍然是在 java 中实现线程安全单例的最佳方式。

于 2013-04-14T17:40:42.417 回答
0

我不鼓励你使用单例(检查这个其他问题

否则,您的代码是线程安全的,因为您所做的唯一影响是在static {}定义上是线程安全的区域中。

顺便说一句,为什么不readPhoneNumber()直接将您的方法合并到您的phone课程中?

于 2013-04-14T17:25:00.497 回答