有时候需要将数据的存储和访问分别放到不同对象中,这时就可以使用访问者模式:
class MultiThreadVector
{
std::vector<int> mArray;
std::mutex mMtx;
public:
class Accessor
{
MultiThreadVector &mData;
std::unique_lock<std::mutex> mGuard;
public:
Accessor(MultiThreadVector &data)
: mData(data), mGuard(data.mMtx)
{
}
void push_back(int value) const
{
return mData.mArray.push_back(value);
}
size_t size() const {
return mData.mArray.size();
}
};
Accessor access() {
return {*this};
}
};