前几天我正在阅读关于单身人士的事情,并考虑在我的一个项目中实施它们,但我不喜欢逻辑上流动的方式,所以我创建了我称之为控制器类来管理单身对象的状态。我想确保逻辑检查出来,并且我不会无意中产生其他实例。
//Controller for SaveSystem, allows the class to be created once for the
//duration of the application at the global level (believe this is called a
//singleton pattern)
public class SaveSystemContr {
private static SaveSystem saveSystemInstance;
public SaveSystem GetSaveSystemData() {
return saveSystemInstance;
}
public void SetSaveSystem(SaveSystem _saveSystem) {
if(saveSystemInstance!=null) {
saveSystemInstance=_saveSystem;
}
}
public static SaveSystem getSaveSystemInstance(final FirebaseAuth _auth, final LoadProjFragment _LFP) {
if(saveSystemInstance==null) {
saveSystemInstance = new SaveSystem(_auth, _LFP);
}
return saveSystemInstance;
}
public SaveSystemContr() {} //THE WAY IS SHUT!
}
编辑*我不认为这是所引用问题的副本,因为这是单例的典型/标准实现,并且它通过利用控制器来管理单例的状态而完全使用不同的模型。 / p>
答案 0 :(得分:1)
我想确保逻辑检出,并且我不会无意中产生其他实例。
看起来您可以根据需要创建任意数量的实例:
SaveSystemContr controller = new SaveSystemContr();
// Create instance 1
controller.SetSaveSystem(new SaveSystem(auth, lfp));
// Create instance 2
controller.SetSaveSystem(new SaveSystem(auth, lfp));
// ...
如果你只想要一个实例,为什么你有一个setter方法?
一个非常基本的单例将如下所示:
public final class SaveSystemSingleton {
// This class should only be accessed statically. Don't allow instance creation
private SaveSystemSingelton() {}
private static SaveSystem saveSystem;
// Encapsulate creation logic. Passing in params is misleading because
// all subsequent calls will do nothing with the params.
public static SaveSystem get() {
// If accessing from multiple threads do Double Check Locking instead!
if (saveSystem == null) {
saveSystem = new SaveSystem(new FirebaseAuth(), new LoadProjFragment());
}
return saveSystem;
}
}
如果你真的需要传入参数,请定义一个单独的静态setter方法,如果多次调用它或者在没有先调用setter的情况下调用get()
,则抛出异常。
另外,你应该检查依赖注入(例如Dagger2),这样可以创建对象的实例并使它们明确而简单。
答案 1 :(得分:1)
将构造函数设为私有并删除getter和setter:
//Allows the OBJECT (not class) to be created once only
public class SaveSystem {
private static SaveSystem saveSystemInstance;
//make constructor private
private SaveSystem(final FirebaseAuth _auth, final LoadProjFragment _LFP) {
//todo complete constructor
}
public static SaveSystem getSaveSystemInstance(final FirebaseAuth _auth, final LoadProjFragment _LFP) {
if(saveSystemInstance==null) {
saveSystemInstance = new SaveSystem(_auth, _LFP);
}
return saveSystemInstance;
}
}
如您所见,它可以在没有控制器的SaveSystem
上应用。