ID生成器创建的对象 [英] ID generator for the Objects created
问题描述
我需要一个类,它创建对象为每个创建的对象分配一个ID。此ID通常是类的int属性。我想要这个值(ID)增加每次一个对象被创建,然后被分配给该对象从1开始。它激励我,我需要一个静态int属性。
I need a class which creates Objects assigning an ID to each Object created. This ID is as usual an int attribute to the class. I want this value (ID) to be increased each time an Object is created and then to be assigned to that Object starting with 1. It strikes me that I need a static int attribute.
如何初始化此静态属性?
How can I initialize this static attribute?
我应该创建一个单独的方法来做ID的增量(作为ID生成器),在构造函数中调用它吗?
Should I create a separate method to do the increment of the ID (as an ID generator) which is invoked inside the constructor?
一般来说,最有效和精心设计的方式是什么?
What is in general the most effective and well-designed manner to implement that?
推荐答案
就像你提到使用 static int
在创建新对象时增加它。
Just like you mention use a static int
for the id, and increment it when creating new objects.
class MyObject {
private static int counter = 0;
public final int objectId;
MyObject() {
this.objectId = counter++;
}
}
请注意,您需要保护 counter ++
如果 MyObject
是由多个线程创建的(例如使用 AtomicInteger
其他答案建议)。
Please note that you need to protect counter++
if MyObject
is created by multiple threads (for example using AtomicInteger
as the other answers suggest).
这篇关于ID生成器创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!