例如,下面的代码片段做了这些事情:首先从数据库中读取数据,然后转换数据,最后将结果写回数据库。进一步来说:
- 从数据库中读取数据并将它们逐条记录存储到A类中。
- 逐条转换存储在 A 类中的数据,B 类完成这项工作。
- 将所有结果存储在 QVariantList 中并批量写入 ihe 数据库。
问题是 A 类、B 类和 ReadTransWrite 类之间的紧密耦合如果我想在 A 类中添加一个成员变量 A4,则需要更改 3 个类。查看以“//-->”开头的评论
如何解耦?有什么模式可以推荐吗?有什么建议吗?
片段:
class A {
public:
void trans(QSqlQuery query){
A1 = query.record().field("A1").value().toString();
A2 = query.record().field("A2").value().toDate();
A3 = query.record().field("A3").value().toInt();
//--> A4 = query.record().field("A4").value().toDouble();
}
public:
QString A1;
QDate A2;
int A3;
//--> double A4;
};
class B {
public:
void trans(const A& a){
B1 = A1;
B2 = A2;
B3 = A3;
//--> B4 = A4;
}
public:
QString B1;
QDate B2;
int B3;
//--> double B4;
};
class ReadTransWrite {
.....
void do();
.....
}
void ReadTransWrite::do(){
....
// prepare for batch insert into the database
QVariantList B1s;
QVariantList B2s;
QVariantList B3s;
//--> QVariantList B4s;
A a; // read record by record from data base
B b; // transform the results record by record
QString sql_read = "select A1, A2, A3 from table0";
//--> QString sql_read = "select A1, A2, A3, A4 from table0";
QSqlQuery query_read;
query_read.exec(sql_read);
while(query_read.next()){
a.trans(query_read); // read record by record from data base
b.trans(a); // transform the results record by record
B1s.push_back(b.B1);
B2s.push_back(b.B2);
B3s.push_back(b.B3);
//--> B4s.push_back(b.B4);
}
QSqlQuery query_write;
QString sql_write = "insert into table (B1, B2, B3) values (:B1, :B2, :B3)";
//--> QString sql_write = "insert into table (B1, B2, B3, B4) values (:B1, :B2, :B3, :B4)";
query_write.prepare(sql_write);
query_write.bindValue(":B1",B1s);
query_write.bindValue(":B2",B2s);
query_write.bindValue(":B3",B3s);
//--> query_write.bindValue(":B4",B4s);
query_write.execBatch();
}