我的应用程序中有超过 20 个常用方法。我想将这 20 个方法移至一个公共(public)类中。
这里我的疑问是,定义所有方法都是静态或普通方法,并创建一个全局对象来访问该普通方法。
class Common {
public String method1() {........}
public String method2() {........}
public String method3() {........}
public String method4() {........}
public String method5() {........}
...
}
创建对象。
class CommonService {
private static Common common;
public static Common getCommon() {
if(null == common) {
common = new common();
}
return common;
}
}
如果我们使用静态方式创建所有方法,则所有 20 个方法都存储在堆的 PermGen 部分中。
但是如果我们按照上面的方法,就只能创建一个对象并将其存储在java堆中。
请说明哪一种是最好的方法。
最佳答案
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
方法不是数据,而是代码。代码的存储位置并不取决于方法是否接受隐式 this
参数。如果使用单例方法,方法代码仍然会占用存储空间,并且堆上还会有一个实例。
但是,以上所有内容都是无关紧要的,您正在关注设计中完全错误的方面。重要的是这个决定将如何影响使用这些方法的代码:
- 静态方法很简单,是纯函数(不依赖于任何外部状态)的绝佳选择;
- 单例允许多态性,因此使方法更容易模拟测试。
关于java - 这是在 java 中执行以下任务的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495407/