Java 中私有建構函式的目的
當我們要限制物件建立的時候,私有建構函式是很有用的。例如,單例模式可以用私有建構函式實現。
示例
public class Tester { private static Tester instance; private Tester(){} public static Tester getInstance(){ if(instance == null){ instance = new Tester(); } return instance; } public static void main(String[] args) { Tester tester = Tester.getInstance(); Tester tester1 = Tester.getInstance(); System.out.println(tester.equals(tester1)); } }
輸出
它會將輸出列印為
true
廣告