Created
October 14, 2016 02:03
-
-
Save remyroez/843830bfa28bf7611a71d36eebac23ee to your computer and use it in GitHub Desktop.
依存性の注入のテスト
This file contains hidden or 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 <iostream> | |
#include <memory> | |
class IFoo | |
{ | |
public: | |
virtual ~IFoo() {} | |
virtual int f() = 0; | |
}; | |
class Foo : public IFoo | |
{ | |
public: | |
Foo() { std::cout << "Foo ctor" << std::endl; } | |
~Foo() { std::cout << "Foo dtor" << std::endl; } | |
int f() override | |
{ | |
return 123; | |
} | |
}; | |
class Foo2 : public IFoo | |
{ | |
public: | |
Foo2() { std::cout << "Foo2 ctor" << std::endl; } | |
~Foo2() { std::cout << "Foo2 dtor" << std::endl; } | |
int f() override | |
{ | |
return 456; | |
} | |
}; | |
class Bar : public IFoo | |
{ | |
public: | |
Bar() : _foo(std::move(std::make_unique<Foo>())) { std::cout << "Bar ctor" << std::endl; } | |
Bar(std::unique_ptr<IFoo>&& foo) : _foo(std::move(foo)) { std::cout << "Bar ctor2" << std::endl; } | |
~Bar() { std::cout << "Bar dtor" << std::endl; } | |
int f() override | |
{ | |
return _foo->f(); | |
} | |
private: | |
std::unique_ptr<IFoo> _foo; | |
}; | |
int main() | |
{ | |
auto foo = std::make_unique<Bar>(); | |
std::cout << foo->f() << std::endl; | |
auto foo2 = std::make_unique<Bar>(std::make_unique<Foo2>()); | |
std::cout << foo2->f() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment