java – 拥有一个类的单个实例,或者只是拥有一堆静态方法更好吗?

前端之家收集整理的这篇文章主要介绍了java – 拥有一个类的单个实例,或者只是拥有一堆静态方法更好吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我一直在使用几种调用方法方法.最近,我一直在使用一个类的静态实例,我相信它是适当的术语(如果我错了,请纠正我).哪个更好(甚至建议想法),为什么?

第一种方式我是简单的旧静态方法.

  1. static void exampleMethod1(){}
  2. static void exampleMethod2(){}

第二种方式(有人说这是一种改进).

  1. public class ExampleClass{
  2. public static ExampleClass instance;
  3. public ExampleClass(){
  4. instance = this;
  5. }
  6. public static ExampleClass getInstance(){
  7. return instance;
  8. }
  9. void exampleMethod1(){
  10. //code
  11. }
  12. void exampleMethod2(){
  13. //code
  14. }
  15. // To call the method I simply getInstance().exampleMethod1
  16. }
最佳答案
你正在寻找的术语是单身人士.

单例上的静态方法和实例方法都是可行的方法,但请注意静态方法方法无法实现接口,因此如果需要实现接口,请使用单例.

例如:

  1. public enum HelloWorld implements Runnable {
  2. INSTANCE;
  3. @Override
  4. public void run() {
  5. System.out.println("Hello,world!");
  6. }
  7. }
  8. // ...
  9. new Thread(HelloWorld.INSTANCE).start();

如果您的hello-world代码是静态方法,则无法直接实现Runnable接口.

猜你在找的Java相关文章