2014-03-31 32 views
1

我有一個Orders類,我需要有一個單例模式以便能夠爲每個處理的訂單創建一個序號。我如何實現這個?如何在java中使用單例模式創建序列號

我的訂單類有一個Order_ID,Customer_ID,Order_desc和Ordered_qty。需要爲每個使用單例模式處理的訂單創建一個序列號。

+2

這似乎不是一個很好的[單例模式](http://en.wikipedia.org/wiki/Singleton_pattern)的用法。爲什麼你需要在數據庫之外生成序列? –

+0

這是作業還是作業? –

+0

是賦值。我必須使用Singleton模式爲每個訂單分配一個序列號。 – user3473791

回答

3

這可能是X/Y問題之一,你認爲Y是X的解決方案,所以你需要Y的幫助,但也許有更好的解決方案。

嚴格地說,要實現一個單例,您只需要一個只有構造函數爲private的類,作爲類字段的類的實例的靜態引用和public getInstance方法。然後創建一個實例方法,它返回下一個數字。

public class MySingleton { 
    private static MySingleton instance = new MySingleton(); 

    private volatile int next = 0; 

    private MySingleton() { 
     // prevent external instantiation of a singleton. 
    } 

    public static MySingleton getInstance() { 
     return instance; 
    } 

    public synchronized int getNextSequence() { 
     return next++; 
    } 
} 

有許多缺陷與此解決您的問題,有的只是基本的OOP設計和一些更系統:

  1. 不執行或延長任何類型的單身是毫無價值的。你可以使用所有的靜態方法。如果你正在編寫一個實現接口的類,並且該接口被其他人使用,但是你只希望單個實例作爲實現細節,那麼單例就很有用。這種單例是試圖使全局變量看起來像它不是全局變量。
  2. 這將不會在應用程序重新啓動後存活。如果使用這些序列來標識存儲在外部或共享的數據,則在重新啓動應用程序時,最終將重複相同的數字。
  3. 如果您部署讀取和寫入常見持久性存儲的應用程序的多個實例(如數據庫),它們將重新使用相同的數字,因爲該序列僅在JVM中進行跟蹤。
  4. 數據庫已經非常好。試圖在應用程序層重新發明它似乎....不適合。
+1

'getInstance'方法應該是靜態的。 –

+0

@OldCurmudgeon方法是同步的 –

+0

修正了,謝謝。還有一個原因是我不喜歡單身。 – Brandon

0

雖然我同意@Elliott Frisch這個問題本身聽起來很奇怪。但是,如果您確實必須自己生成標識,那麼這裏是實現經典 Singleton模式版本的原型。

public class IdGenerator { 
    private static IdGenerator instance; 
    private int id = 0; 
    private IdGenerator(){} 
    private static IdGenerator getInstance() { 
     synchronized(IdGenerator.class) { 
      if (instance == null) { 
       instance = new IdGenerator(); 
      } 
      return instance; 
     } 
    } 

    public int nextId() { 
     return id++; 
    } 
} 

請注意,單詞「經典」。 Singleton模式有很多可能的改進,並且有數百篇文章解釋它們。

0

關鍵方面是使用單個AtomicLong作爲單例。你可以這樣建模:

class Orders { 

    private static final AtomicLong NEXT_ID = new AtomicLong(); 

    static Order newOrder(Customer customer, String description, int quantity) { 
     return new Order(orderId(), customer, description, quantity); 
    } 

    private static long orderId() { 
     return NEXT_ID.incrementAndGet(); 
    } 
} 

class Order { 

    private final long orderId; 
    private final long customerId; 
    private final String description; 
    private final int quantity; 

    Order(long orderId, Customer customer, String description, int quantity) { 
     this.orderId = orderId; 
     this.quantity = quantity; 
     this.customerId = customer.getCustomerId(); 
     this.description = description; 
    } 

} 

class Customer { 

    public long getCustomerId() { 
     throw new UnsupportedOperationException("not yet implemented"); 
    } 
}