如果我想生成一个具有随机值的简单对象的 Java 实例。
例如,对于类:
class Entity {
int id;
}
我想添加生成函数,用 id 的随机值初始化一个新实例。
最好的 OOP 方法是什么?我考虑了 2 个选项:
在实体类中创建静态方法:
class Entity {
int id;
public static Entity generate(){
Entity e = new Entity ();
int rand = MathUtil.generateRandomInt(); // method in util class
in the project.
e.setId(rand )
return e;
}
}
创建 EntityGenerator 类:
class EntityGenerator{
public Entity generate(){
Entity e = new Entity ();
int rand = MathUtil.generateRandomInt(); // method in util class
in the project.
e.setId(rand);
return e;
}
}
我犹豫什么是更好的选择。
您只需要创建一个类的对象。它会自动填充随机数..
import java.util.Random;
public class Entity {
private int id;
public Entity() {
id = new Random().nextInt(100000);//set the upper limit, it generated numbers between 0 and 99999
}
public int getId() {
return id;
}
public Entity setId(int id) {
this.id = id;
return this;
}
}
或者你可以在类中创建一个静态的 Random()
对象。
public class Entity {
private static Random r = new Random();
private int id;
public Entity() {
id = r.nextInt(100000);//set the upper limit, it generated numbers between 0 and 99999
}
public int getId() {
return id;
}
public Entity setId(int id) {
this.id = id;
return this;
}
}
希望对您有所帮助。