どんなもの?
- あるクラスにおける機能追加と機能実装の2つの継承を分離し、それらを独立して管理する
- 機能追加のための継承: スーパークラスが持っていない機能をサブクラスで追加する
- 機能実装のための継承: スーパークラスで定義したインターフェースでサブクラスで実装する
- カプセル化を超えて、絶縁する
どんなときに使う?
- 上記の2種類の継承関係が混在しているときに、機能追加を行いたいとき
例
構成要素
- Abstraction
- RefinedAbstracton
- Implementor
- 機能実装の継承関係の最上位クラス。
- Abstractionの使用する関数のインターフェースを定義する
- ConcreteImplementor
- Implementorの定めたインターフェースを実装する
- Client
コード
#include <iostream>
#include <string>
using namespace std;
class Implementor{
public:
virtual void print(string something) = 0;
};
class ConcreteImplementor: public Implementor{
public:
void print(string something){
cout << something << endl;
}
};
class Abstraction{
public:
Abstraction(Implementor *impl){
this->impl = impl;
}
void print(string something){
impl->print(something);
}
protected:
Implementor *impl;
};
class RefinedAbstraction: public Abstraction{
public:
RefinedAbstraction(Implementor *impl):Abstraction(impl){}
void bracketPrint(string something){
cout << "\"" << endl;
impl->print(something);
cout << "\"" << endl;
}
public:
};
int main(){
RefinedAbstraction refinedAbs(new ConcreteImplementor);
refinedAbs.bracketPrint("test");
return 0;
}