Java:只允许一个类实例化
我希望项目中的某些课程能够被合并。因此,我不希望能够使用 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); }
...
}
现在我可以通过将默认构造函数设置为私有来禁用正常的实例化方式,但问题是池需要在创建类时实例化该类,并且当池需要扩展时也需要实例化该类。
有什么办法可以限制施工只能在泳池边进行吗?
I want certain classes in my project to be pooled. And so I don't want to be able to instantiate these classes using: new SomeClass(), but instead obtain a new item from the pool using SomeClass.allocate().
I have this kind of code for each class that needs pooling.
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); }
...
}
Now I can disable the normal way of instantiating by making the default constructor private, but the problem is that the pool needs to instantiate the class when it's created, and also when the pool needs to expand.
Is there some way to limit construction to only by the pool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可以看到你有两个选择:要么将其设为池的内部类,要么将分配方法设为包私有并将其放在与池相同的包中。
编辑:啊。只需将构造函数设置为私有,然后重写池用于创建新实例的任何方法即可。作为使用上面框架的(原始)示例:
并且
GameObject
的构造函数很高兴其他任何人都无法访问。You have 2 options I can see: either make it an inner-class of the pool or make the
allocate
method package-private and put it in the same package as the pool.EDIT: Ah. Just make the constructor private and then override whatever method the
Pool
uses to create new instances. As a (crude) example using your frame above:and
GameObject
's constructor is happily inaccessible to anyone else.作为最后的手段,您可以使用反射。对于其他选择,其他人已经告诉过。
我记得Spring容器能够初始化具有私有构造函数的类。我对此感到惊讶。我猜它也用了这个技巧。好处可能是它更通用。
As a last resort,you are able to use reflection. For other option,other people already tells.
I remember Spring container is able to init class that has private constructor. And I am surprised of that. I guess it also uses this trick. The benefit could be it is more generic.
替代方案:不要试图让你的代码跳过障碍。使用静态分析来执行这样的规则。如果您不小心做了一些无意的事情,这些工具就会捕获它。
Alterative: Don't try to make your code jump through hoops. Use static analysis to enforce rules like this. The tools will catch it if you accidentally do something that you didn't intend to.