Dart redirect to another class based on the result of condition

Viewed 23

I have method ConnectToDb() in two classes. One connects to database with direct connection and second connects to database with api. In that classes I have other functions for retrive data from db which uses same methods as ConnectToDb() (direct or via api). What can I do to make it easier to refer to the right class after checking the setting value? My classes:

class1{
  void readData(){
    connectionSetting = readConnectionSetting();
    if (connectionSetting==0){ // What I have to do with that if statement? Want to remove that because 
                               // I have so many classes with data reading functions and don't want to 
                               // check settings everywhere.
      List<...> data = getData();
    }
  }
}


directConnectionClass{
  List<...> getData(){
    ...
    direct connect and read data
    ...
    return data;
  }
}

apiConnectionClass{
  List<...> getData(){
    ...
    connect via api and read data
    ...
    return data;
  }
}
1 Answers

If I understand the question correctly, you're actually looking for the decorator pattern.

The root class should basically wrap the other two classes, so the structure would look like:

class root {
  directConnectionClass directObj;
  apiConnectionClass apiObj;
  void readData(){
    connectionSetting = readConnectionSetting();
    if (connectionSetting==0){ 
      List<...> data = directObj.getData();
    }
    else {
      List<...> data = apiObj.getData();
    }
  }
}
...
Related