【发布时间】:2012-04-28 05:31:04
【问题描述】:
有时,由于集合,我会遇到一个类的单个实例就足够的情况。我的解码器类就是一个例子:
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;
}
}
但我在想,为什么不让它看起来像这样:
public class Decoder
{
private static final HashMap<Client, State> states = new HashMap<Client, State>();
public static Packet decode(Client client, ByteBuffer data)
{
return null;
}
}
两种设计都有效地完成了同样的事情。两者有什么实际区别吗?我什么时候会使用其中一个?谢谢。
【问题讨论】:
-
所有这些都谈到了单例对于实现接口等是多么有用。我的场景不需要这样。不过,感谢您指出这些重复项。