これは、休止状態にも倹約自体にも関係ありません。
Hibernate を介してデータベースからデータをフェッチし、Apache thrift サービスを介してそれらのオブジェクトを提供したい Java アプリケーションを開発しています。これまでのところ、いくつかのモデルしかありませんが、モデルごとに、休止状態のオブジェクト リストを反復処理し、thrift obects のリストを構築する必要があります。
たとえば、次のコードを考えてみましょう (これは、Hibernate コレクションを IN として受け取り、thrift コレクションを返す、thrift サービス ハンドラーです)。
@Override
public List<TOutcome> getUserOutcomes(int user_id) throws TException {
List<Outcome> outcomes = this.dataProvider.getOutcomesByUserId(user_id);
List<TOutcome> result = new ArrayList<>();
for (Iterator iterator = outcomes.iterator(); iterator.hasNext();) {
Outcome outcome = (Outcome) iterator.next();
TOutcome t_outcome = new TOutcome(
(double) (Math.round(outcome.getAmount() * 100)) / 100,
outcome.getUser().getName(),
String.valueOf(outcome.getCategory().getName()));
t_outcome.setComment(outcome.getComment());
result.add(t_outcome);
}
return result;
}
@Override
public List<TIncome> getUserIncomes(int user_id) throws TException {
List<Income> incomes = this.dataProvider.getIncomesByUserId(user_id);
List<TIncome> result = new ArrayList<>();
for (Iterator iterator = incomes.iterator(); iterator.hasNext();) {
Income income = (Income) iterator.next();
TIncome t_income = new TIncome(
(double) (Math.round(income.getAmount() * 100)) / 100,
income.getUser().getName(),
String.valueOf(income.getCategory().getName()));
t_income.setComment(income.getComment());
result.add(t_income);
}
return result;
}
Outcome
, Income
- これらは Hibernate アノテーション付きクラスでありTOutcome
、 , TIncome
- 関連するthrift オブジェクト (フィールドの 80-90% を共有) です。
このコードは非常によく似ているため、「DRY」の原則に違反しています。休止状態のオブジェクトを反復処理し、thrift オブジェクトを返す 1 つの汎用メソッドを提供したいと思います。ジェネリックとデザインパターンを考えていました。
動的言語では、文字列を使用してクラス名を作成し、オブジェクトを構築できます (型チェックはありません)。ジェネリックを使用してJavaで同様のことを行う可能性があると思いますが、どこから始めるべきかわかりません。