用enum枚举类实现单例模式

来源:互联网 发布:电子版世界名画淘宝店 编辑:程序博客网 时间:2024/06/01 12:55

用enum枚举类实现单例模式:

public enum FastDFSClient {    instances;    private StorageClient1 storageClient1 = null;    private Logger logger = LoggerFactory.getLogger(FastDFSClient.class);    FastDFSClient() {        TrackerClient tracker = new TrackerClient();        StorageServer storageServer = null;        TrackerServer trackerServer = null;        while (true) {            try {                trackerServer = tracker.getConnection();                storageServer = tracker.getStoreStorage(trackerServer);                break;            } catch (IOException e) {                logger.error("create fastDFS fail retry");                try {                    TimeUnit.SECONDS.sleep(1);                } catch (InterruptedException e1) {                    logger.warn("thread interrupt");                }            }        }        this.storageClient1 = new StorageClient1(trackerServer, storageServer);    }    public void init(Map<String, String> map) throws Exception {        Properties initPropertie = new Properties();        //只需要设置ip, 其余的使用默认值即可        initPropertie.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS, map.get(BrowserConstants.FASTDFS_SERVERS));        ClientGlobal.initByProperties(initPropertie);        TrackerClient tracker = new TrackerClient();        TrackerServer trackerServer = tracker.getConnection();        if (!ProtoCommon.activeTest(trackerServer.getSocket())) {            throw new Exception("无法连接到fastDFS");        }    }    public String uploadFile(byte[] contents) {        try {            return storageClient1.upload_file1(contents, null, null);        } catch (Exception e) {            logger.error("fastDFS save error", e);            return null;        }    }    public int deleteFile(String file_id) throws Exception {        try {            return storageClient1.delete_file1(file_id);        } catch (Exception e) {            logger.error("fastDFS delete error.", e);            return 0;        }    }    public int truncateFile(String appender_file_id) {        try {            return storageClient1.truncate_file1(appender_file_id);        } catch (Exception e) {            logger.error("fastDFS truncate error", e);            return 0;        }    }}