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");
}
}
這似乎是一個矯枉過正的問題,有沒有更好的方法來解決他的問題? – 2011-09-27 22:30:30