簡體   English   中英

使用非靜態公共最終變量公開實例常量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM