1 2 #include <fruit/fruit.h> 3 #include <iostream> 4 5 using fruit::Component; 6 using fruit::Injector; 7 8 class Writer { 9 public: 10 virtual void write(std::string s) = 0; 11 }; 12 13 class StdoutWriter : public Writer { 14 public: 15 // Like "StdoutWriter() = default;" but also marks this constructor as the 16 // one to use for injection. 17 INJECT(StdoutWriter()) = default; 18 write(std::string s)19 virtual void write(std::string s) override { 20 std::cout << s; 21 } 22 }; 23 24 class Greeter { 25 public: 26 virtual void greet() = 0; 27 }; 28 29 class GreeterImpl : public Greeter { 30 private: 31 Writer* writer; 32 33 public: 34 // Like "GreeterImpl(Writer* writer) {...}" but also marks this constructor 35 // as the one to use for injection. INJECT(GreeterImpl (Writer * writer))36 INJECT(GreeterImpl(Writer* writer)) : writer(writer) {} 37 greet()38 virtual void greet() override { 39 writer->write("Hello world!\n"); 40 } 41 }; 42 getGreeterComponent()43Component<Greeter> getGreeterComponent() { 44 return fruit::createComponent().bind<Writer, StdoutWriter>().bind<Greeter, GreeterImpl>(); 45 } 46 main()47int main() { 48 49 Injector<Greeter> injector(getGreeterComponent); 50 Greeter* greeter = injector.get<Greeter*>(); 51 52 greeter->greet(); 53 54 return 0; 55 } 56