在C++中,文件操作流的设计模式通常涉及以下几个方面:
单例模式(Singleton Pattern):
class FileStream {
private:
static FileStream* instance_;
FileStream() {}
public:
static FileStream* getInstance() {
if (!instance_) {
instance_ = new FileStream();
}
return instance_;
}
void write(const std::string& data) {
// 写入文件操作
}
std::string read() {
// 读取文件操作
return "";
}
};
FileStream* FileStream::instance_ = nullptr;
工厂模式(Factory Pattern):
class FileStreamFactory {
public:
static std::unique_ptr<FileStream> createFileStream(const std::string& type) {
if (type == "binary") {
return std::make_unique<BinaryFileStream>();
} else if (type == "text") {
return std::make_unique<TextFileStream>();
}
return nullptr;
}
};
class BinaryFileStream : public FileStream {
// 二进制文件流实现
};
class TextFileStream : public FileStream {
// 文本文件流实现
};
观察者模式(Observer Pattern):
class FileStreamSubject {
private:
std::vector<std::shared_ptr<FileStreamObserver>> observers_;
public:
void addObserver(std::shared_ptr<FileStreamObserver> observer) {
observers_.push_back(observer);
}
void removeObserver(std::shared_ptr<FileStreamObserver> observer) {
observers_.erase(std::remove(observers_.begin(), observers_.end(), observer), observers_.end());
}
void notifyObservers() {
for (auto& observer : observers_) {
observer->update();
}
}
void write(const std::string& data) {
// 写入文件操作
notifyObservers();
}
};
class FileStreamObserver {
public:
virtual void update() = 0;
};
class FileWriter : public FileStreamObserver {
public:
void update() override {
// 处理写入操作
}
};
策略模式(Strategy Pattern):
class FileWriteStrategy {
public:
virtual void write(std::ostream& os, const std::string& data) = 0;
};
class BinaryWriteStrategy : public FileWriteStrategy {
public:
void write(std::ostream& os, const std::string& data) override {
// 二进制写入操作
}
};
class TextWriteStrategy : public FileWriteStrategy {
public:
void write(std::ostream& os, const std::string& data) override {
// 文本写入操作
}
};
class FileStream {
private:
std::unique_ptr<FileWriteStrategy> writeStrategy_;
public:
FileStream(std::unique_ptr<FileWriteStrategy> strategy) : writeStrategy_(strategy) {}
void write(const std::string& data) {
writeStrategy_->write(std::cout, data);
}
};
int main() {
auto binaryStrategy = std::make_unique<BinaryWriteStrategy>();
FileStream fileStream(binaryStrategy);
fileStream.write("Hello, World!");
auto textStrategy = std::make_unique<TextWriteStrategy>();
FileStream textFileStream(textStrategy);
textFileStream.write("Hello, World!");
return 0;
}
这些设计模式可以帮助你更好地组织和管理C++中的文件操作流,提高代码的可维护性和可扩展性。