我必须维护一个代码,以便为类中的最终静态变量增加更多的灵活性。
该变量不再是全局常数,可以更改。
问题在于该类在一个公共库中,并且在不同的项目中使用。
您是否有比将类代码从通用库复制并粘贴到我的特定应用程序并进行重构更好的方法或设计模式?
例子:
公地项目
Class CommonClass {
public final static var globalSomething = somethingGlobal;
public static method(){ //CommonClass.globalSomething is used here}
}
在我的应用程序(和其他引用公用程序的应用程序)中,我们可以使用static属性并调用该方法:
---> var b = CommonClass.somethingGlobal;
---> var c = CommonClass.method() //we know that CommonClass.globalSomething is used here
期望:
如果我说对了,您想将此作为参数来实现。
看你的例子:
var c = CommonClass.method() //we know that CommonClass.globalSomething is used here
已经有问题了。CommonClass.somethingGlobal
在调用该方法之前,您不必知道必须正确设置。这样,客户必须知道实现方式,这违反了信息隐藏的原理。如果需要该值,则将其作为参数引入:
Class CommonClass {
public static void method(var globalSomething){}
}
一种替代方法是使变量和方法均为非静态,并使用构造函数:
Class CommonClass {
public var globalSomething = somethingGlobal;
public CommonClass(var globalSomething) {
this.globalSomething = globalSomething;
}
public void method(){}
}
PS:您的示例代码不是Java。我在回答中部分纠正了它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句