概要
リポジトリパターンとは、デザインパターンの一つである。
現代だと、DDDとセットで履修することが前提で使用する。
DDDでの依存関係でいうと以下のような形になる。
graph TD A[application層(Notifier/Service)] --> B(domain層 Interface); C[infrastructure層(Repositoryそのもの)] --> B; style B fill:#a0ffc0,stroke:#333 style C fill:#ffc0a0,stroke:#333
ここで、infra層でRepositoryを使用する。
データの永続化を行う。(または、DataSourceを通して。)
コード
Dartで書いていくが、基本的な考え方は同じである。
@freezed
sealed class Person extends _$Person {
const factory Person({
required String name,
required int age
}) = _Person;
}これは、永続化対象のコード(データ)。
そしてDomain層でリポジトリのインターフェースを記述する。
abstract class ILocalDataBaseRepository {
Future<void> save(String key, int data);
Future<CountData?> load(String key);
}infra層で具象クラスを作成する。
class SharedPrefsRepositoryImpl implements ISharedPrefsRepository {
@override
Future<Data?> load(String key) async {
final value = db.getInt(key.value);
return Data(data: value);
}
@override
Future<void> save(String key, int data) async {
await prefs.setInt(key, data);
}
}この時、DBを操作するライブラリやDBが変更しても、このリポジトリの具象クラスを変更するだけで済むという考え方が、リポジトリパターン(DDD)である。
このリポジトリはDomain層のユースケースインターフェースを具象化したクラスから呼び出す。
旧記事
概要
リポジトリパターンとは、デザインパターンの一つである。
端的に言うと、モデルクラスと動作クラスを分けることで何か仕様変更があった時に柔軟に対処することが出来るものである。
Transclude of リポジトリパターンの図
コード
ここでは、Dartでコードの例を示す。
//モデルクラス
class Person{
late final _name;
late final _age;
Peson(this._name, this._age);
}
//リポジトリクラス
class DBManeger{
void create(){ ... }
void read(){ ... }
void update(){ ... }
void delete(){ ... }
}
//DBの操作クラス
class DBCreater{ ... }
class DBReader{ ... }
class DBUpdateer{ ... }
class DBDeleter{ ... }