2010-02-17 45 views
1

我想寫一個以C1000開頭的靜態類客戶ID,並且爲每個創建的新客戶對象添加+1,C1001,C1002,C1003 , 等等。如果有字符串,它是如何完成的?如何編寫一個靜態類,該靜態類有一個帶有字符串的ID

public class Customer 
{ 
    private static int customerID = 1000; 

    public Customer() 
    { 
     customerID++; 
    } 

    public static int getcutomerID() 
    { 
     return customerID; 
    } 
} 

回答

3
public class Customer { 
    private static int customerID = 1000; 

    // wth would you do this?! static state is evil! 
    public Customer() { customerID++; } 

    public String getCurrentCustomerID() { return "C" + customerID; } 
} 

靜態測試非常不好。它相當於全局變量。也許是一個更好的設計是:

public class Customer { 
    private final int id; 
    public Customer(final int id) { this.id = id; } 
    public int getId() { return id; } 
} 

public class CustomerDatabase { 
    private int nextId; 

    public CustomerDatabase() { this(0); } 
    public CustomerDatabase(int nextId) { this.nextId = nextId; } 

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

    // define useful operations for a CustomerDatabase 
} 

// maybe you could use the database and customer classes as follows 
public class CustomerApplication { 
    public static void main(String[] args) { 
     // first argument is highest customer id 
     CustomerDatabase db = new CustomerDatabase(Integer.parseInt(args[0])); 

     Customer c = new Customer(db.nextId()); 
     db.add(c); 

     System.out.println(db.getCustomers()); 

     db.save("customers.txt"); 

     Customer x = db.findById(13); 
     if(x.isBroke()) db.delete(x); 

     System.out.println("K thx, bai"); 
    } 
} 
+0

這似乎是一個矯枉過正的問題,有沒有更好的方法來解決他的問題? – 2011-09-27 22:30:30

6
public class Customer { 
    private static int NextCustomerId = 1000; 
    private final int myCustomerId; 

    public Customer() { 
     myCustomerId = NextCustomerId++; 
     ... 
    } 

    public String getCustomerId() { 
     return "C" + myCustomerId; 
    } 
} 

請注意,這可能不是線程安全的。如果您需要它,請查看java.util.concurrent.atomic.AtomicInteger並將其中的一個用於NextCustomerId

+2

nah ...他最好不要使用靜態變量......他應該分開關注從Customer類發佈新的客戶id - 可能會創建一個IdGenerator(或CustomerDatabase,因爲我已包含在修改的響應中)。使測試是否不存在靜態變得很容易。如果您有靜態狀態,序列化如何工作?一些問題隨着......靜態而出現...... – les2 2010-02-17 04:14:22

相關問題