0
 public enum Singleton  {
            INSTANCE;
            String fromLocation;
            String toLocation;

            private void initialise(String fromLocation, String toLocation) {
                this.fromLocation = fromLocation;
                this.toLocation = toLocation;
            }

            public static void main(String[] args) {
                Singleton s = INSTANCE;
                s.initialise(args[0],args[1]);
            }
    }

メインルーチンからも引数を渡すことができる通常のJavaクラスコンストラクターを持つ構文を理解できないようです。初期化ルーチンは私には悪臭のように思えますが、これは私が思いついた中で最高のものです。助言がありますか?

4

3 に答える 3

0

あなたはおそらく次のようなことを意味しています:

public class Singleton {
  private static Singleton instance;
  public static void getInstance() {
    if (instance == null)
      throw new IllegalStateException("Singleton not initialized!");
    return instance;
  }
  public static void init(String from, String to) {
    if (instance != null)
      throw new IllegalStateException("Singleton already initialized!");
    instance = new Singleton(from, to);
  }
  private final String from;
  private final String to;
  private Singleton(String from, String to) {
    this.from = from;
    this.to = to;
  }
}

明らかに、これはスレッドセーフなどではありません。しかし、正直なところ、Spring や Guice などの依存性注入フレームワークを使用した方がよいでしょう。コード内のこのSingleton.getInstance()呼び出しは、長期的には望んでいるものではありません...

列挙型を使用/定義しないのはなぜですか? 「列挙型は、変数を定義済みの定数のセットにすることを可能にする特別なデータ型です」と書かれています。Javaチュートリアルで。そして、あなたは明らかにいくつかの定数を扱っていません。

于 2013-09-18T23:11:44.837 に答える