Skip to content

Instantly share code, notes, and snippets.

@niosus
Created July 4, 2016 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save niosus/d2293f89e1808ae44a3737bb39963d50 to your computer and use it in GitHub Desktop.
Save niosus/d2293f89e1808ae44a3737bb39963d50 to your computer and use it in GitHub Desktop.
An example of builder pattern in c++
#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