how to write a static class that has an id with a string in it
I want to write a static class customer ID that begins with C1000, and for each new customer object created it will add +1, C1001, C1002, C1003, and so on. 开发者_开发百科How is it done if there is a string?
public class Customer
{
private static int customerID = 1000;
public Customer()
{
customerID++;
}
public static int getcutomerID()
{
return customerID;
}
}
public class Customer {
private static int NextCustomerId = 1000;
private final int myCustomerId;
public Customer() {
myCustomerId = NextCustomerId++;
...
}
public String getCustomerId() {
return "C" + myCustomerId;
}
}
Note that this probably isn't threadsafe. If you need it to be, look at java.util.concurrent.atomic.AtomicInteger and use one of those for NextCustomerId
.
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; }
}
Static state is very bad for testing. It amounts to global variables. Perhaps a better design is:
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");
}
}
Don't do that. Use an int
with String.format()
.
精彩评论