您是否会考虑使用接口和多态来扩展此设计以进行过度设计?
优点
缺点
我的直觉是,对于这种特殊情况,单个if语句和布尔标志是最好的选择,但不是每个人都同意我.
行什么,你觉得呢?
原版的
// Connects to a local pipe, and naturally
// owns that connection
struct CommandWriter
{
CommandWriter() {
fd = open("/path/to/fifo", O_WRONLY);
if (fd == -1)
throw std::runtime_error("Could not establish connection to FIFO");
};
~CommandWriter() {
close(fd);
};
// (Has useful member functions here)
private:
CommandWriter(CommandWriter const&); // Not relevant to question
int fd;
};
Run Code Online (Sandbox Code Playgroud)
使用布尔标志扩展
// Adds a constructor where an FD can be specified
// from the call site, and no ownership is taken
struct CommandWriter
{
CommandWriter() : owns_fd(true) {
fd = open("/path/to/fifo", O_WRONLY);
if (fd == -1)
throw std::runtime_error("Could not establish connection to FIFO");
};
CommandWriter(int fd) : fd(fd), owns_fd(false) {};
~CommandWriter() {
if (owns_fd)
close(fd);
};
// (Has useful member functions here)
private:
CommandWriter(CommandWriter const&); // Not relevant to question
int fd;
bool owns_fd;
};
Run Code Online (Sandbox Code Playgroud)
扩展多态性
// Sorry for the poor type names!
struct ICommandWriter
{
virtual ICommandWriter() {}
// (Has useful member functions here)
private:
ICommandWriter(ICommandWriter const&); // Not relevant to question
};
struct CommandWriter_Connects : ICommandWriter
{
CommandWriter_Connects() {
fd = open("/path/to/fifo", O_WRONLY);
if (fd == -1)
throw std::runtime_error("Could not establish connection to FIFO");
};
~CommandWriter_Connects() {
close(fd);
};
// (Has useful member functions here)
private:
int fd;
};
struct CommandWriter_Uses : ICommandWriter
{
CommandWriter_Uses(int fd) : fd(fd) {};
~CommandWriter_Uses() {};
// (Has useful member functions here)
private:
int fd;
};
Run Code Online (Sandbox Code Playgroud)
这取决于你将使用它.如果你有一个大项目,并且会多次使用该类的变体,那么确保它具有灵活性是有意义的.
经验法则:
当然有很多例外,但这是一个起点.
你为什么不复制文件描述符?这样,当对象被销毁时,你可以关闭()它并让操作系统处理剩下的事情:
CommandWriter::CommandWriter (int _fd) : fd (dup (_fd)) {};
Run Code Online (Sandbox Code Playgroud)
为此添加一个布尔标志就是发明了一个轮子.使用多态性正在构建一架frigging直升机.