本文介绍了使用适配器设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我致力于实现适配器设计模式以利用现有类.我的问题是,这些类的工作方式几乎相同,但在另一个类上具有不同的名称和较少的功能.

I was working on implementing an adapter design pattern to utilize the existing classes. My problem is, the classes works almost same, but have different names and less functionalities on another.

例如,每个Work类和Homework类都有一个功能相同的函数,即doWork()doHomework().
我可以将这些链接到 Task 界面中的 doThis().但是,Work 类没有 done() 函数,而 Homework 类有它.我将如何照顾这个?就是没有执行?有没有更好的方法?

For example, each Work class and Homework class has one function that does the same, which is doWork() and doHomework().
I can link these to doThis() in Task interface. But, Work class doesn't have done() function while Homework class has it. How would I take care of this? Just no implementation? Are there any better approach?

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...
}

推荐答案

适配器使用多重继承的实现(目标是公共的,被适配者是私有的)是一种有效的方法.

The adapter implementation using multiple inheritance (public for the target, private for the adaptee) is a valid approach.

只需注意函数的返回类型:

Just take care of the the return type of the function:

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() 的功能时,您必须模拟它.所以这不仅仅是改变名称,还要确保类似的行为:

When no feature is available for taking care of done() in the adaptee, you must emulate it. So its's not just about changing the name, but also ensuring similar behaviour:

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
  }
};

这篇关于使用适配器设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 15:23