Dart
Repository
Repository pattern öğrenirsin.
Repository
Repository pattern, veri erişimini soyutlar. Alan katmanı bir Repository arayüzü tanımlar; veri katmanı bunu uygular. Alan, verinin API'den mi veritabanından mı geldiğini bilmez.
Örnek: abstract class ProductRepository { Product fetch(String id); }. Somut sınıflar: ApiProductRepository, DbProductRepository, MockProductRepository — hepsi aynı arayüzü uygular.
Avantaj: testte MockProductRepository kullanılır; gerçek API'ye bağlanmadan alan mantığı sınanır. Veri kaynağı değişince sadece somut sınıf değişir.
Çoklu veri kaynakları
Aynı arayüzü birden çok sınıf uygulayabilir: ApiRepo (uzak API), DbRepo (yerel veritabanı), CacheRepo (önbellek). Uygulama, hangisini kullanacağına yapılandırma ile karar verir.
Önbellek stratejisi: CacheRepo önce önbelleğe bakar; miss olursa ApiRepo'ya düşer ve sonuçu önbelleğe yazar. Bu desen dekoratör (decorator) olarak bilinir.
Repository arayüzü değişmeden, iç uygulama istenildiği gibi değiştirilebilir. Bu, kodun bakımını ve genişletilmesini kolaylaştırır.
Uygulama ProductRepository ve Mock tanımla
Bir Product sınıfı tanımla: final String id; final String name; Product(this.id, this.name);. Bir abstract class ProductRepository tanımla: Product fetch(String id);. Bir class MockProductRepository implements ProductRepository tanımla: @override Product fetch(String id) => Product(id, 'Kitap');. main içinde final repo = MockProductRepository(); yarat; final product = repo.fetch('1'); ve print(product.name); ekle.
Örnek çözümü göster
class Product {
final String id;
final String name;
Product(this.id, this.name);
}
abstract class ProductRepository {
Product fetch(String id);
}
class MockProductRepository implements ProductRepository {
@override
Product fetch(String id) => Product(id, 'Kitap');
}
void main() {
final repo = MockProductRepository();
final product = repo.fetch('1');
print(product.name);
}
Kendini test et
-
Repository parçalarını eşleştir
- Repository
- Sözleşme
- RepositoryImpl
- Uygulama
- fetch(id)
- Okuma metodu
- save(entity)
- Yazma metodu
-
Repository pattern neyi soyutlar?
- Arayüz çizimini
- Veri erişimini
- Test çalıştırmayı
- Dosya okumayı
Cevabı göster
Veri erişimini — Repository veri erişimini soyutlar; kaynak gizli kalır.
-
Repository uygulaması
class ApiUserRepository ____ UserRepository { }
Cevabı göster
class ApiUserRepository implements UserRepository { }
Sıradaki ders: Dependency injection