良いアプローチをファクトリパターンを使用することです。ファクトリは、オブジェクトのインスタンスを生成するオブジェクトです。次に、すべてのオブジェクトに対してIDを管理できる1つの場所があります。
にオブジェクトを登録することもできます。 IDを手渡すオフィスのように。使用量がより快適に行うためのシングルトンパターンを使用して
登録オフィス、::ここで
登録方法を使用した例である
public class IdProvider {
private static IdProvider instance = null;
public IdProvider getInstance() {
if (instance == null) {
instance = new IdProvider();
}
return instance;
}
private int nextID = 0;
public int getUniqueId() {
if (nextId < 0) {
throw new IllegalStateException("Out of IDs!");
}
int uniqueId = nextId;
nextId++;
return uniqueId;
}
}
あなたオブジェクト:
public class Vehicle {
String make;
String model;
int year;
int id;
double bill;
public Vehicle() {
// Get an ID
this.id = IdProvider.getInstance().getUniqueId();
}
}
public class Car extends Vehicle {
private int noDoors;
public Car(String make, String model, int year, int noDoors) {
// An ID is fetched implicitly because
// the super-constructor of Vehicle is
// always called
this.noDoors = noDoors;
this.make = make;
this.model = model;
this.year = year;
}
}
あなたは迅速かつ汚いソリューションを探している場合は別の方法として、あなたはVehicle
に静的カウンターを使用することができます。
public class Vehicle {
private static int nextId = 0;
String make;
String model;
int year;
int id;
double bill;
public Vehicle() {
// Get an ID
this.id = Vehicle.nextId;
// Increase the ID for the next vehicle
Vehicle.nextId++;
}
}
静的変数は、クラスのすべてのインスタンス間で共有されます。だから、すべての車両にはただ1つのnextId
オブジェクトがあり、それらはすべてそれにアクセスできます。
あなたは並列環境(マルチスレッドプログラミング)でそのコードを使用する場合、あなたはIdProvider
のgetUniqueId
方法で世話をしなければならないことに注意してください。
synchronize
が必要です。または、idカウンタのタイプをAtomicInteger
に置き換えて、AtomicInteger#getAndIncrement
(documentation)のようなスレッドセーフメソッドを提供することもできます。
この宿題はありますか?実際に何か試しましたか? – Oleg
DBを使用してデータを格納します。これが単なるテストプログラムであれば、おそらくシングルトンを使うことができます。このコードに複数のスレッドがアクセスした場合に何が起きるか注意してください。 – TeaCode
これを見てください:https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems – larsgrefer