![](/img/trans.png)
[英]Do final (constant) instance (non-static) variables act like class (static) variables?
[英]Exposing instance constants with non-static public final variables
我从来没有在我周围的任何Java代码中看到这种常量声明...所以我想知道你是否看到使用非静态最终常量的任何缺点。
例如,我已经将Guava函数声明为给定MaintenanceMode实例的公共常量。 我认为这更好,因为如果我创建了一个getDecoratorFunction(),它每次都会创建一个新的函数实例...
或者get函数可以返回在类中保持私有的单实例函数,但它有无用的代码......当我们在类级别声明常量时,我们直接声明常量是公共的,我们不将它们设置为私有并提供公众获取者访问他们......
public class MaintenanceMode {
/**
* Provides a function to decorate a push service with the appropriate decorator
*/
public final Function<PushService,PushService> MAINTENANCE_DECORATION_FUNCTION = new Function<PushService,PushService>() {
@Override
public PushService apply(PushService serviceToDecorate) {
return new PushServiceMaintenanceDecorator(serviceToDecorate,MaintenanceMode.this);
}
};
private final EnumMaintenanceMode maintenanceMode;
private final long milliesBetweenMaintenances;
private final Optional<ExecutorService> executorService;
public EnumMaintenanceMode getMaintenanceMode() {
return maintenanceMode;
}
public long getMilliesBetweenMaintenances() {
return milliesBetweenMaintenances;
}
public Optional<ExecutorService> getExecutorService() {
return executorService;
}
private MaintenanceMode(EnumMaintenanceMode maintenanceMode, long milliesBetweenMaintenances, ExecutorService executorService) {
Preconditions.checkArgument(maintenanceMode != null);
Preconditions.checkArgument(milliesBetweenMaintenances >= 0);
this.maintenanceMode = maintenanceMode;
this.milliesBetweenMaintenances = milliesBetweenMaintenances;
this.executorService = Optional.fromNullable(executorService);
}
}
我可以通过以下方式访问此变量:
pushServiceRegistry.decoratePushServices(maintenanceMode.MAINTENANCE_DECORATION_FUNCTION);
我想如果我的maintenanceMode是可变的并且被多个线程访问,它可能会导致奇怪的行为,但在这里它不是。
你觉得使用这种代码有什么缺点吗?
编辑:我可以有多个MaintenanceMode实例,并且所有实例都应该能够根据MaintenanceMode状态提供不同的常量函数。 所以我不能使用不能访问MaintenanceMode状态的静态变量。
吸气剂的关键是动态调度。 如果您不需要它,使用public final
字段是完全正常的。 我甚至经常编写没有getter的bean类对象,只是public final
字段。
通过使一个常量非静态,你基本上说只有当你有一个该类的实例时才能访问常量。 但它是公开的(在MAINTENANCE_DECORATION_FUNCTION
的情况下)并且它是该类的一部分所以为什么不使它静态? 毕竟,常量是常量,并且不需要在其他地方使用该类的实例。 变量maintenanceMode
很好,因为它是一个私有常量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.