2023年4月29日 星期六

C++:簡介 Prototype 模式

本文為 C++ Software Design 書的第 30 節內容。 Prototype pattern 的目的是提供複製物件的抽象 API。以下為一個複製動物的例子:


class Animal {
public:
  virtual ~Animal() = default;
  // Prototype design pattern
  virtual std::unique_ptr<Animal> clone() const = 0;
};

class Sheep : public Animal {
public:
  explicit Sheep(std::string name) : name_{std::move(name)} {}
  std::unique_ptr<Animal> clone() const override;
private:
  std::string name_;
};

std::unique_ptr<Animal> Sheep::clone() const {
  // Copy-construct a sheep
  return std::make_unique<Sheep>(*this);
}
使用 unique_ptr 的原因是利用 smart pointer 的特性來回收這個指標。 Prototype pattern 與 std::variant 有些類似;不同的是 std::variant 中的類別在定義後就是固定的,而 Prototype pattern 只要能繼承 base class 便能自由地擴充。