在C++中,文件操作流的設(shè)計模式通常涉及以下幾個方面:
單例模式(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 {
// 二進(jìn)制文件流實現(xiàn)
};
class TextFileStream : public FileStream {
// 文本文件流實現(xiàn)
};
觀察者模式(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 {
// 二進(jìn)制寫入操作
}
};
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;
}
這些設(shè)計模式可以幫助你更好地組織和管理C++中的文件操作流,提高代碼的可維護(hù)性和可擴(kuò)展性。