我正在努力实现适配器设计模式以利用现有的类。我的问题是,类的工作方式几乎相同,但在另一个类上有不同的名称和较少的功能。
例如,每个工作类和 Homework 类都有一个功能相同,即 doWork()和 doHomework()即可。
我可以将这些链接到任务界面中的 doThis()。但是,工作课程没有完成()功能,而家庭作业课程有。我该如何处理这件事?只是没有实施?还有更好的方法吗?
class Task {
public:
virtual int doThis() = 0;
virtual bool done() = 0;
};
class Work {
public:
Work();
int doWork();
};
class Homework {
public:
Homework();
int doHomework();
bool done();
bool isDone;
};
class WorkAdapter : public Task, private Work {
public:
WorkAdapter();
int doThis() {
return doWork();
}
virtual bool done() {
// Is this okay not to implment this?
}
};
class HomeworkAdapter : public Task, private Homework {
public:
HomeworkAdapter();
int doThis() {
return doWork();
}
virtual bool done() {
return isDone;
}
};
int main() {
Task *homework = new HomeworkAdapter();
Task *work = new WorkAdapter();
homework->doThis();
bool isHomeworkDone = homework->done();
work->doThis();
bool isWorkDone = work->done(); // This would never be called in my implementation...
}
答案 0 :(得分:1)
使用多重继承的adapter实现(目标为public,适配器为private)是一种有效的方法。
只需处理函数的返回类型:
class HomeworkAdapter : public Task, private Homework {
public:
HomeworkAdapter() {}
int doThis() override { // make sure you override target member
return doWork(); // and return value as expected
}
bool done() override {
return isDone;
}
};
提示:不需要在派生类中指定virtual。相反,值得使用覆盖,以避免在不匹配的参数或返回类型的情况下出现细微问题。
如果没有功能可用于处理适配器中的done()
,则必须模拟它。所以它不仅仅是改变名称,还要确保类似的行为:
class WorkAdapter : public Task, private Work {
bool isdone; // functionality to add
public:
WorkAdapter() : isdone(false) {}
int doThis() override {
auto rc = doWork();
isdone = true; // once it's done, it's done ;-)
return rc;
}
bool done() override {
return isdone; // you must add this
}
};