1 回答

TA貢獻1854條經驗 獲得超8個贊
正如您所說,它是使用單例模式實現的,因此您需要使用Instance方法而不是構造函數。由于 constructor 上的 private 修飾符private GoPiGo3(int addr, boolean detect)...,它只能從 GoPiGo3 類中調用。
public static GoPiGo3 Instance() throws IOException, FirmwareVersionException{
if (_instance == null) {
_instance = new GoPiGo3(8, true);
}
return _instance;
}
public static GoPiGo3 Instance(int addr) throws IOException, FirmwareVersionException{
if (_instance == null) {
_instance = new GoPiGo3(addr, true);
}
return _instance;
}
public static GoPiGo3 Instance(boolean detect) throws IOException, FirmwareVersionException{
if (_instance == null) {
_instance = new GoPiGo3(8, detect);
}
return _instance;
}
public static GoPiGo3 Instance(int addr, boolean detect) throws IOException, FirmwareVersionException{
if (_instance == null) {
_instance = new GoPiGo3(addr, detect);
}
return _instance;
}
要獲取GoPiGo3實例,您需要執行以下操作:
GoPiGo3 platform = GoPiGo3.Instance(8,true);
參考:
https://www.geeksforgeeks.org/singleton-class-java/
添加回答
舉報