Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

dart - How to approach repository pattern in Flutter having both Database and Server interactions

I am starting a new app and I'd like to integrate the repository pattern in the architecture, however I am not sure what is the right approach to do so, when I am planning to interact with both a server and a local database.

Approach 1: Having two separated repository classes (1 for database and 1 for server interactions).

abstract class ItemRepositoryInterface {}

class ItemDatabaseRepository extends ItemRepositoryInterface {
  final Database _database;
  ItemDatabaseRepository(this._database);

  getAllItems() {
    // implement database interaction
  }
}

class ItemServerRepository extends ItemRepositoryInterface {
  final HttpClient _httpClient;

  ItemServerRepository(this._httpClient);

  getAllItems() {
    // implement server interaction
  }
}

Approach 2: One class for both

class ItemRepository extends ItemRepositoryInterface {
  Database database;
  HttpClient httpClient;

  ItemRepository({
    this.database,
    this.httpClient,
  });

  getAllItemsFromDatabase() {
    // implement database interaction
  }
  getAllItemsFromServer() {
    // implement server interaction
  }
}

Approach 3: Named constructors

(this approach seems to me the least scaleable, I added here to show all cases I was thinking about)

class ItemRepository extends ItemRepositoryInterface {
  Database database;
  HttpClient httpClient;

  ItemRepository.server(this.httpClient);
  ItemRepository.database(this.database);

  getAllItems() {
    if (this.httpClient == null && this.database != null) {
      _getAllItemsFromDatabase();
    }
    if (this.database == null && this.httpClient != null) {
      _getAllItemsFromServer();
    }
  }

  _getAllItemsFromDatabase() {
    // implement database interaction
  }
  _getAllItemsFromServer() {
    // implement server interaction
  }
}

Im grateful for your input


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...