1 /* 2 * Copyright 2014 Google Inc. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include <fruit/fruit.h> 18 #include <iostream> 19 20 using fruit::Component; 21 using fruit::Injector; 22 23 class Listener { 24 public: 25 virtual void notify() = 0; 26 }; 27 28 class Listener1 : public Listener { 29 public: 30 INJECT(Listener1()) = default; 31 notify()32 void notify() override { 33 std::cout << "Listener 1 notified" << std::endl; 34 } 35 }; 36 37 class Writer { 38 public: 39 virtual void write(std::string s) = 0; 40 }; 41 42 // To show that we can inject parameters of multibindings 43 class StdoutWriter : public Writer { 44 public: 45 INJECT(StdoutWriter()) = default; 46 write(std::string s)47 void write(std::string s) override { 48 std::cout << s << std::endl; 49 } 50 }; 51 52 class Listener2 : public Listener { 53 private: 54 Writer* writer; 55 56 public: INJECT(Listener2 (Writer * writer))57 INJECT(Listener2(Writer* writer)) : writer(writer) {} 58 notify()59 void notify() override { 60 writer->write("Listener 2 notified"); 61 } 62 }; 63 getListenersComponent()64Component<> getListenersComponent() { 65 // Here they are in the same component to keep it simple, but Fruit collects all multibindings in installed 66 // components. 67 return fruit::createComponent() 68 .bind<Writer, StdoutWriter>() 69 .addMultibinding<Listener, Listener1>() 70 .addMultibinding<Listener, Listener2>(); 71 } 72 main()73int main() { 74 Injector<> injector(getListenersComponent); 75 std::vector<Listener*> listeners = injector.getMultibindings<Listener>(); 76 77 // The order of the returned listeners is unspecified, so the lines in output may have any order. 78 for (Listener* listener : listeners) { 79 listener->notify(); 80 } 81 82 return 0; 83 } 84