Jac*_*cob 5 java methods static class
我一直在使用几种调用方法的方法.最近,我一直在使用一个类的静态实例,我相信它是适当的术语(如果我错了,请纠正我).哪个更好(甚至建议想法),为什么?
第一种方式我是简单的旧静态方法.
static void exampleMethod1(){}
static void exampleMethod2(){}
Run Code Online (Sandbox Code Playgroud)
第二种方式(有人说这是一种改进).
public class ExampleClass{
public static ExampleClass instance;
public ExampleClass(){
instance = this;
}
public static ExampleClass getInstance(){
return instance;
}
void exampleMethod1(){
//code
}
void exampleMethod2(){
//code
}
// To call the method I simply getInstance().exampleMethod1
}
Run Code Online (Sandbox Code Playgroud)
你正在寻找的术语是单身人士.
单例上的静态方法和实例方法都是可行的方法,但请注意静态方法方法无法实现接口,因此如果需要实现接口,请使用单例.
例如:
public enum HelloWorld implements Runnable {
INSTANCE;
@Override
public void run() {
System.out.println("Hello, world!");
}
}
// ...
new Thread(HelloWorld.INSTANCE).start();
Run Code Online (Sandbox Code Playgroud)
如果您的hello-world代码是静态方法,则无法直接实现该Runnable接口.
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |