所有静态方法还是单个实例? [英] All static methods or a single instance?
本文介绍了所有静态方法还是单个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时候,由于集合的缘故,我想出了一个类的单个实例就足够了的情况.一个例子就是我的Decoder类:
Sometimes, I come up with situations where a single instance of a class is enough, thanks to collections. An example would be my Decoder class:
public class Decoder
{
private static final Decoder instance = new Decoder();
private final HashMap<Client, State> states = new HashMap<Client, State>();
private Decoder()
{
}
public Packet decode(Client client, ByteBuffer data)
{
return null;
}
}
但是我在想,为什么不做它,使它看起来像这样:
But I was thinking, why not just make it so it looks something like:
public class Decoder
{
private static final HashMap<Client, State> states = new HashMap<Client, State>();
public static Packet decode(Client client, ByteBuffer data)
{
return null;
}
}
两种设计都可以有效地完成相同的任务.两者之间有什么实际区别吗?我什么时候可以使用另一个?谢谢.
Both designs effectively accomplish the same thing. Is there any practical difference in the two? When would I use one over the other? Thanks.
推荐答案
我会使用所有静态方法,除非您看到需要实现一个接口,例如这样您就可以模拟或替换您的实例.
I would use all static methods, unless you see the need to implement an interface e.g. so you can mock out or replace your instance.
public enum Decoder implements IDecoder {
INSTANCE;
private final Map<Client, State> states = new HashMap<Client, State>();
public Packet decode(Client client, ByteBuffer data) {
return null;
}
}
或
public enum Decoder {;
private static final Map<Client, State> states = new HashMap<Client, State>();
public static Packet decode(Client client, ByteBuffer data) {
return null;
}
}
这篇关于所有静态方法还是单个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文