Javaインターフェースの返り値をラップするメソッド
Java では、インターフェイスの戻り値をカプセル化する場合は、次のような方法を使用できます。
- エンティティクラスを使用する:エンティティクラスを作成してインターフェースの返り値を格納します。エンティティクラスには、返す必要があるデータのフィールドが含まれており、適切なgetterメソッドとsetterメソッドが用意されています。インターフェースの返り値は、このエンティティクラスのオブジェクトになります。
サンプルコード:
public class Result {
private int code;
private String message;
// getter and setter methods
// other methods if needed
}
public interface MyInterface {
Result doSomething();
}
class MyClass implements MyInterface {
public Result doSomething() {
Result result = new Result();
result.setCode(200);
result.setMessage("Success");
return result;
}
}
- Mapコレクションを利用する:インターフェースの戻り値はMapコレクションを用いてカプセル化することができます。Mapコレクションはキーと値のペアを格納でき、キーにデータの種別、値に具体的なデータを格納します。インターフェースの戻り値はこのMapコレクションオブジェクトになります。
サンプルコード:
public interface MyInterface {
Map<String, Object> doSomething();
}
class MyClass implements MyInterface {
public Map<String, Object> doSomething() {
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("message", "Success");
return result;
}
}
- カスタムラッパークラスを使用する: インターフェイスの戻り値をラップするため、カスタムのラッパークラスを作成することができます。そのラッパークラスは、さまざまなタイプのデータを格納するために、複数のフィールドを含めることができます。
ネイティブな日本語で文章を言い換える必要があります。オプションは1つだけです。例:
public class Response<T> {
private int code;
private String message;
private T data;
// getter and setter methods
// other methods if needed
}
public interface MyInterface {
Response<String> doSomething();
}
class MyClass implements MyInterface {
public Response<String> doSomething() {
Response<String> response = new Response<>();
response.setCode(200);
response.setMessage("Success");
response.setData("Hello World");
return response;
}
}
ここでは、各種の封じ込めインターフェイスの戻り値のメソッドを要約しました。具体的な選択肢は、実際の要件やプロジェクトのアーキテクチャに基づいて決定します。