Java:仅允许一类实例化

ter*_*hau 5 java constructor

我希望将项目中的某些类合并。因此,我不想使用以下方法实例化这些类:new SomeClass(),而是使用SomeClass.allocate()从池中获取一个新项目。对于需要池化的每个类,我都有这种代码。

public class GameObject
{
    // Pooling: Provides a static method for allocation and a method for freeing
    private static Pool<GameObject> pool = new Pool<GameObject>();
    public static GameObject allocate() { return pool.obtain(); }
    public void free() { pool.free(this); }
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,我可以通过将默认构造函数设为私有来禁用常规的实例化方法,但是问题是,池在创建类时以及在需要扩展池时都需要实例化该类。

有什么方法可以限制仅在游泳池旁施工吗?

Fem*_*emi 2

我可以看到你有两个选择:要么将其作为池的内部类,要么将方法设为allocate包私有并将其放在与池相同的包中。

编辑:啊。Pool只需将构造函数设为私有,然后重写用于创建新实例的任何方法即可。作为使用上面框架的(粗略)示例:

public abstract class Pool<T>
{
    public abstract T getNewObject();

    public T obtain(){ return getNewObject(); }

    public void free(T obj) {}
}
Run Code Online (Sandbox Code Playgroud)

public class GameObject
{
    // Pooling: Provides a static method for allocation and a method for freeing
    private static Pool<GameObject> pool = new Pool<GameObject>(){
          public GameObject getNewObject(){ return new GameObject(); }
    };
    public static GameObject allocate() { return pool.obtain(); }
    private GameObject(){}
    public void free() { pool.free(this); }
}
Run Code Online (Sandbox Code Playgroud)

GameObject很高兴其他人无法访问 的构造函数。