-
-
Save WenxiJin/28366bd1abee92dd8ad9c768bc111b93 to your computer and use it in GitHub Desktop.
An example of builder pattern in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <memory> | |
class BBuilder; | |
class A { | |
public: | |
A() {} | |
virtual ~A() { fprintf(stderr, "A done.\n"); } | |
int getA() const { return _a; } | |
virtual void print() const { fprintf(stderr, "_a=%d\n", _a); } | |
private: | |
int _a = 101; | |
}; | |
class B : public A { | |
friend BBuilder; | |
public: | |
virtual ~B() { fprintf(stderr, "B done.\n"); } | |
int getParam() const { return _param; } | |
int getAnotherParam() const { return _another_param; } | |
void print() const override { | |
fprintf(stderr, "_param=%d\n", _param); | |
fprintf(stderr, "_another_param=%d\n", _another_param); | |
} | |
private: | |
B() : A{} {} | |
int _param = 20; | |
int _another_param = 20; | |
}; | |
class BBuilder { | |
public: | |
BBuilder() { _b.reset(new B); } | |
virtual ~BBuilder() { fprintf(stderr, "Builder done.\n"); } | |
BBuilder& withParam(int param) { | |
if (_b) { | |
_b->_param = param; | |
} | |
return *this; | |
} | |
BBuilder& withAnotherParam(int param) { | |
if (_b) { | |
_b->_another_param = param; | |
} | |
return *this; | |
} | |
std::unique_ptr<B> build() { return std::move(_b); } | |
private: | |
std::unique_ptr<B> _b = nullptr; | |
}; | |
int main(int argc, char const* argv[]) { | |
std::unique_ptr<A> a = | |
BBuilder().withParam(100).withAnotherParam(200).build(); | |
fprintf(stderr, "Builder should be dead now.\n"); | |
a->print(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment