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

created : Tue, 07 Apr 2020 20:44:17 +0900
modified : Sat, 26 Sep 2020 23:16:07 +0900

객체 생성

중복처리

struct Address
{
  string street, city;
  int suite;
}
struct Contact
{
  string name;
  Address address;
}

struct Contact
{
  string name;
  Address* address;
}
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;
  }
};

요약