枚举单例模式简单实践,用枚举构建一个百度API的client唯一实例。
public enum BaiduApi {
API;
public static final String APP_ID = "43543";
public static final String API_KEY = "K9dpjF0HqltT534ePgPuhQCrhsG";
public static final String SECRET_KEY = "8fd9WaY7BeKkT34534KMY3rIs3oSSFmzxRep0";
private AipNlp client;
private BaiduApi(){
client=new AipNlp(APP_ID, API_KEY, SECRET_KEY);
}
public AipNlp getClient(){
return this.client;
}
}
测试类
@Test
public void testBaiduApi(){
System.out.println(BaiduApi.API.getClient());
System.out.println(BaiduApi.API.getClient());
System.out.println(BaiduApi.API.getClient());
}
结果为
com.baidu.aip.nlp.AipNlp@65e579dc
com.baidu.aip.nlp.AipNlp@65e579dc
com.baidu.aip.nlp.AipNlp@65e579dc
在程序运行过程中获取的是唯一的client。