Является ли этот дизайн чрезмерным?

Не могли бы вы использовать интерфейс и полиморфизм для расширения этого

Плюсы

  • Расширяемый
  • Инкапсулированный
  • Авто-магический

Минусы

  • Намного больше кода
  • Немного громоздко в использовании (вам придется использовать другой имя типа, чтобы получить другое поведение)
  • Может быть менее эффективным в использовании из-за вызовов виртуальных функций.

Мне кажется, что для этого конкретного случая один оператор 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;
};

Расширенный с логическим флагом

// 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;
};

Расширенный с полиморфизмом

// 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;
};
]
7
задан user7116 5 April 2012 в 18:04
поделиться