【问题标题】:All static methods or a single instance?所有静态方法还是单个实例?
【发布时间】: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;
    }
}

两种设计都有效地完成了同样的事情。两者有什么实际区别吗?我什么时候会使用其中一个?谢谢。

【问题讨论】:

标签: java static instance


【解决方案1】:

如果您想对使用 Decoder(或任何其他“实用程序”对象)的类进行单元测试,您可能需要模拟它 - 即,将 Decoder 替换为行为如下的虚拟对象已知。这样,如果 Decoder 类发生变化,您的单元测试不会中断。

如果Decoder 是一个实际对象,这将更容易实现。如果Decoder 是一个充满静态方法的类,你就不能真正轻松地模拟它(尽管有一些模拟框架可以通过修改字节码来实现这一点)。

简而言之,静态方法是一种可测试性反模式。我强烈建议不惜一切代价避免它们。如果您想了解更多相关信息,请尝试http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/ - 该网站上还有很多其他关于可测试性的好建议。

【讨论】:

    【解决方案2】:

    我会使用所有静态方法,除非您看到需要实现接口,例如这样您就可以模拟或替换您的实例。

    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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      我认为在客户端类中编码时使用静态方法会更短,

      public class Collections {
         // Suppresses default constructor, ensuring non-instantiability.
         private Collections() {
         }
      
         public static <T extends Comparable<? super T>> void sort(List<T> list) {
             ...
         }
      }
      

      那么我们有,

      Collections.sort(list);
      

      【讨论】:

      • 我也是这么想的。静态方法更短——你只需加上静态修饰符。
      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      相关资源
      最近更新 更多