Home | History | Annotate | Download | only in testing
      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 "cached_greeter.h"
     18 #include "key_value_storage.h"
     19 
     20 class CachedGreeterImpl : public Greeter {
     21 private:
     22   Greeter* greeter;
     23   KeyValueStorage* keyValueStorage;
     24 
     25 public:
     26   INJECT(CachedGreeterImpl(Greeter* greeter, KeyValueStorage* keyValueStorage))
     27     : greeter(greeter), keyValueStorage(keyValueStorage) {
     28   }
     29 
     30   std::string greet() override {
     31     std::string greeting = keyValueStorage->get("greeting");
     32     if (!greeting.empty()) {
     33       return greeting;
     34     }
     35 
     36     // Not in the cache, we need to compute the greeting.
     37     greeting = greeter->greet();
     38 
     39     // We also add it in the cache so that later calls don't need to call greeter->greet().
     40     keyValueStorage->put("greeting", greeting);
     41 
     42     return greeting;
     43   }
     44 };
     45 
     46 fruit::Component<fruit::Annotated<Cached, Greeter>> getCachedGreeterComponent() {
     47   return fruit::createComponent()
     48       .bind<fruit::Annotated<Cached, Greeter>, CachedGreeterImpl>()
     49       .install(getKeyValueStorageComponent)
     50       .install(getGreeterComponent);
     51 }
     52