C++ 设计模式之适配器模式
简介
1、适配器模式(Adapter)是一种结构型设计模式,它允许将一个类的接口转换成客户端所期望的另一种接口,从而使得原本由于接口不兼容而无法协同工作的类能够一起工作。这种模式的主要作用是将原本不兼容的接口转换为兼容的接口,使得原本无法协同工作的类能够协同工作。
2、适配器模式 (Adapter)应用场景包括但不限于:
2.1、当你希望使用某个类,但是它的接口与其他代码不兼容时,使用适配器模式。
2.2、当你想创建一个可以与其他类合作的可复用类,且不想改变这些类的源代码时。
2.3、在需要对旧代码进行重用,但其接口并不符合系统的新需求时使用。
3、适配器模式(Adapter)的构成
3.1、旧接口
class OldPrinter
{
public:
void printDocument(const std::string& doc);
};
3.2、新接口
class DocumentPrinter
{
public:
virtual void print() = 0;
};
3.3、适配器
class PrinterAdapter : public DocumentPrinter
{
public:
PrinterAdapter(const std::string& doc);
void print();
private:
OldPrinter oldPrinter;
std::string document;
};
4、适配器模式(Adapter)的优点
4.1、提高了类的复用性: 通过将现有的类包装到适配器中,它们就可以无缝地与其他接口合作。
4.2、增强了代码可维护性: 如果需要更换系统中的某个组件,适配器可以将新组件适配到现有代码中,而不需要修改原有系统。
4.3、更好的代码解耦: 客户端代码不需要知道实现细节,只需要通过目标接口与适配器进行交流。
4.4、符合开闭原则: 可以引入新的适配器来适配新的类型,而不需要修改客户端代码。
5、适配器模式(Adapter)的缺点
5.1、增加了系统复杂性: 引入适配器会增加系统中的类的数量,增加系统的维护成本。
5.2、有时可能只是一种临时方案: 适配器可能只是对旧代码的一种包装,可能不会从根本上解决接口不匹配的问题。
简单示例
1、定义
// 旧接口
class OldPrinter
{
public:
void printDocument(const std::string& doc);
};
// 新接口
class DocumentPrinter
{
public:
virtual void print() = 0;
};
// 适配器
class PrinterAdapter : public DocumentPrinter
{
public:
PrinterAdapter(const std::string& doc);
void print();
private:
OldPrinter oldPrinter;
std::string document;
};
2、实现
void OldPrinter::printDocument(const std::string& doc)
{
std::cout << "OldPrinter:" << doc << std::endl;
}
PrinterAdapter::PrinterAdapter(const std::string& doc) : document(doc)
{
}
void PrinterAdapter::print()
{
oldPrinter.printDocument(document);
}
3、调用
std::string doc = "这是一个接口适配";
DocumentPrinter* pDoc = new PrinterAdapter(doc);
pDoc->print();
delete pDoc;