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/
添加回答
举报