Singleton的應用很普及,特別是在java的web項目中。比例項目的一些請求外部平臺的地址、商戶號或項目的圖片訪問路徑、模板生成的路徑等等。接下看看示例代碼你就明白了。
/**
*
* @description Singleton(單例)
* since this isn't inherited from a cloneable
* base class and cloneability isn't added,
* making it final prevents cloneability from
* being added in any derived classes
* @author tangfq;
* @version 2020年4月3日 上午11:35:20
*
**/
final class Singleton {
/*
* 當定義一個static變量的時候JVM會將其分配到內存堆上,
* 所有程序對它的引用都會指向這一個地址而不會重新分配內存.
*/
private static Singleton s=new Singleton(47);
private int i;
private Singleton(int x){
i=x;
}
/**
* static修改一個程序塊的時候(也就是直接將代碼寫在static{...}中)時候,JVM就會優先加載靜態
* 塊中代碼,這主要用於系統初始化。
* @return
*/
public static Singleton getHandle(){
return s;
}
public int getValue(){
return i;
}
public void setValue(int x){
i=x;
}
public static void main(String[] args) {
Singleton s=Singleton.getHandle();
System.out.println(s.getValue());
Singleton s2=Singleton.getHandle();
s2.setValue(4);
System.out.println(s.getValue());
System.out.println("兩個對象是否引用同一地址:"+(s==s2));
}
}
關於static和final更詳細的說明。請參考我的blog:https://blog.csdn.net/developerFBI/article/details/105157093.