我有一个类,它有一个 Initialize 方法,它在数据库中创建一堆表。这个类看起来像这样:
public class MyClass
{
private bool initialized = false;
public void Initialize()
{
if(!initialized)
{
//Install Database tables
initialized = true;
}
}
public void DoSomething()
{
//Some code which depends on the database tables being created
}
public void DoSomethingElse()
{
//Some other code which depends on the database tables being created
}
}
DoSomething 和 DoSomethingElse 这两个方法需要确保在继续之前调用了 Initialize 方法,因为它们依赖于数据库中的表。我有两个选择:
在类的构造函数中调用 Initialize 方法 - 这似乎不是一个好主意,因为构造函数现在应该调用方法,这些方法很重要,可能会导致异常。
在这两种方法中的每一种中调用 Initialize 方法 - 这似乎也不是一个很好的解决方案,尤其是在有多个方法的情况下。
是否有一种设计模式可以更优雅地解决这个问题?
最佳答案
我会使用 static factory method其中 Initialize
被调用,并将构造函数设为私有(private),以强制使用静态工厂方法:
public class MyClass
{
private MyClass() { ... }
public static MyClass createInstance() {
MyClass instance = new MyClass();
instance.Initialize();
return instance;
}
}
此外,我会删除 initialized
变量 - 部分原因是您不再需要它 - 但也因为它需要一些保证可见性的方法(例如同步、volatile 或 AtomicBoolean
) 用于线程安全。
我认为 Miško Hevery's关于(不)在构造函数中工作的博客文章很有趣。
关于java - 需要初始化对象时使用的设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36843301/