Modern C++ Design Pattern/Chatper 4. 프로토타입

created : 2020-04-07T11:44:17+00:00
modified : 2020-09-26T14:16:07+00:00

객체 생성

struct Contact { string name; Address* address; }

* 복제 생성자를 통한 중복 초기화
* 복제 생성자를 배제하고 별도의 인터페이스
```cpp
template <typename T> struct Clonable
{
  virtual T clone() const = 0;
}

직렬화(Serialization)

struct Contact
{
  string name;
  Address* address = nullptr;
  private:
  friend class boost:serialization::access;
  template<class Ar> void serialize(Ar& ar, const unsigned int version)
  {
    ar & name;
    ar & address; // *가 없다는 것에 주의
  }
};


auto clone = [](const Contact& c)
{
  ostringstream oss;
  boost::achive::text_oarchive oa(oss);
  oa << c;
  string s = oss.str();

  istringstream iss(oss.str());
  boost::arhive::text_iarchive ia(iss);
  Contact result;
  ia >> result;
  return result;
}

프로토타입 팩터리

struct EmployeeFactory
{
  static Contact main;
  static Contact aux;

  static unique_ptr<Contact> NewMainOfficeEmployee(string name, int suite)
  {
    return NewEmployee(name, suite, main);
  }

  static unique_ptr<Contact> NewAuxOfficeEmployee(string name, int suite)
  {
    return NewEmployee(name, suite, aux);
  }

  private:
  static unique_ptr<Contact> NewEmployee(string name, int suite, Contact& proto)
  {
    auto result = make_unique<Contact>(proto);
    result->name = name;
    result->address->suite = suite;
    return result;
  }
};

요약