#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
class Data
{
public:
Data() {}
Data(string strData) : m_strData(strData) {}
void setData(const string& strData) { m_strData = strData; }
const string& getData() { return m_strData; }
virtual const string operation() { return m_strData; }
private:
string m_strData;
};
class DataManager : public Data
{
public:
DataManager() {}
DataManager(Data* pobjData) : m_pobjData(pobjData) {}
virtual const string operation() override
{
if (!m_pobjData)
{
return m_pobjData->operation();
}
return string();
}
void setData(Data* pobjData) { m_pobjData = pobjData; }
protected:
Data* m_pobjData = nullptr;
};
class SaveData : public DataManager
{
public:
SaveData() {}
SaveData(SaveData* pobjSaveData) : DataManager(pobjSaveData) {}
virtual const string operation() override
{
string strData = m_pobjData->operation();
cout << "保存数据" << strData << endl;
return strData;
}
};
class ClassicalEncryptData : public DataManager
{
public:
ClassicalEncryptData() { this->initializeKeys(); }
ClassicalEncryptData(ClassicalEncryptData* pobjClassicalEncryptData) : DataManager(pobjClassicalEncryptData) { this->initializeKeys(); }
void initializeKeys()
{
m_mapKeys.clear();
for (int i = 0; i < 26; i++)
{
m_mapKeys.insert(make_pair('a' + i, 'a' + ((i + 3) % 26)));
}
}
virtual const string operation() override
{
string strData = m_pobjData->operation();
map<char, char> mapKeys = m_mapKeys;
transform(strData.begin(), strData.end(), strData.begin(), [&mapKeys](const char& ch){ return mapKeys.find(ch) == mapKeys.end() ? ' ' : mapKeys[ch]; });
cout << strData << endl;
return strData;
}
private:
map<char, char> m_mapKeys;
};
int main()
{
Data* pobjData = new Data("hello");
SaveData* pobjSaveData = new SaveData();
ClassicalEncryptData* pobjClassicalEncryptData = new ClassicalEncryptData();
pobjClassicalEncryptData->setData(pobjData);
pobjSaveData->setData(pobjClassicalEncryptData);
pobjSaveData->operation();
return 0;
}
总结:Data类保存数据,DataManager类对Data类进行装饰,SaveData类和ClassicalEncryptData类为具体的装饰类。装饰模式可以有选择地、按顺序地进行装饰
装饰模式
最新推荐文章于 2024-05-29 20:23:07 发布