如何编写一个id为字符串的静态类

Ter*_*rry 1 java

我想编写一个以C1000开头的静态类客户ID,对于每个创建的新客户对象,它将添加+1,C1001,C1002,C1003等.如果有字符串怎么办?

public class Customer
{
    private static int customerID = 1000;

    public Customer()
    {
        customerID++;
    }

    public static int getcutomerID()
    {
        return customerID;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*tto 6

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

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

    public String getCustomerId() {
        return "C" + myCustomerId;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这可能不是线程安全的.如果你需要它,请查看java.util.concurrent.atomic.AtomicInteger并使用其中一个NextCustomerId.

  • nah ...他最好不要使用静态变量......他应该将从客户类发出新客户ID的问题分开 - 可能会创建一个IdGenerator(或者我已经包含在修改后的响应中的CustomerDatabase) .如果没有静态状态,可以轻松测试.如果你有静态状态,序列化如何工作?一些问题刚刚出现......静态...... (2认同)