#include <iostream>
using namespace std;
// 1. 创建实现部分的接口
class Implementor {
public:
virtual void operationImpl() = 0;
};
// 2. 实现部分具体类A
class ConcreteImplementorA : public Implementor {
public:
void operationImpl() override {
cout << "Concrete Implementor A" << endl;
}
};
// 3. 实现部分具体类B
class ConcreteImplementorB : public Implementor {
public:
void operationImpl() override {
cout << "Concrete Implementor B" << endl;
}
};
// 4. 抽象部分的接口
class Abstraction {
protected:
Implementor* implementor;
public:
void setImplementor(Implementor* impl) {
implementor = impl;
}
virtual void operation() = 0;
};
// 5. 抽象部分具体类
class AbstractionImpl : public Abstraction {
public:
void operation() override {
implementor->operationImpl();
}
};
// 6. 客户端代码
int main() {
Abstraction* abs = new AbstractionImpl();
abs->setImplementor(new ConcreteImplementorA());
abs->operation();
abs->setImplementor(new ConcreteImplementorB());
abs->operation();
// 释放内存
delete abs->implementor;
delete abs;
return 0;
}
版权归属:
WenzhouXv
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区