C ++通过生成器实例化对象

问题描述 投票:0回答:1

我最近了解了设计模式,我已经阅读了有关构建器模式的文章,https://riptutorial.com/cplusplus/example/30166/builder-pattern-with-fluent-api。我对对象的实例化有疑问。这是文章中的代码:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

// Forward declaring the builder
class EmailBuilder;

class Email
{
  public:
    friend class EmailBuilder;  // the builder can access Email's privates

    static EmailBuilder make();

    string to_string() const {
        stringstream stream;
        stream << "from: " << m_from
               << "\nto: " << m_to
               << "\nsubject: " << m_subject
               << "\nbody: " << m_body;
        return stream.str();
    }

  private:
    Email() = default; // restrict construction to builder

    string m_from;
    string m_to;
    string m_subject;
    string m_body;
};

class EmailBuilder
{
  public:
    EmailBuilder& from(const string &from) {
        m_email.m_from = from;
        return *this;
    }

    EmailBuilder& to(const string &to) {
        m_email.m_to = to;
        return *this;
    }

    EmailBuilder& subject(const string &subject) {
        m_email.m_subject = subject;
        return *this;
    }

    EmailBuilder& body(const string &body) {
        m_email.m_body = body;
        return *this;
    }

    operator Email&&() {
        return std::move(m_email); // notice the move
    }

  private:
    Email m_email;
};

EmailBuilder Email::make()
{
    return EmailBuilder();
}

// Bonus example!
std::ostream& operator <<(std::ostream& stream, const Email& email)
{
    stream << email.to_string();
    return stream;
}


int main()
{
    Email mail = Email::make().from("[email protected]")
                              .to("[email protected]")
                              .subject("C++ builders")
                              .body("I like this API, don't you?");

    cout << mail << endl;
}

有人可以解释Email mail = Email::make().from("[email protected]"),它是如何工作的?

c++ oop design-patterns c++builder
1个回答
0
投票

Email::make()返回Email的新实例,该实例由m_email修改(实际上是其成员from()),该实例返回实例的引用,从而允许再次由to()进行修改,等等。定义转换的运算符允许获取Email。注意friend class EmailBuilder允许EmailBuilder访问/修改Email]的私有字段

© www.soinside.com 2019 - 2024. All rights reserved.