001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.cache;
016
017import com.google.common.annotations.GwtIncompatible;
018import com.google.common.base.Preconditions;
019import com.google.common.collect.ImmutableMap;
020import java.util.concurrent.ExecutionException;
021
022/**
023 * A cache which forwards all its method calls to another cache. Subclasses should override one or
024 * more methods to modify the behavior of the backing cache as desired per the <a
025 * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
026 *
027 * <p>Note that {@link #get}, {@link #getUnchecked}, and {@link #apply} all expose the same
028 * underlying functionality, so should probably be overridden as a group.
029 *
030 * @author Charles Fry
031 * @since 11.0
032 */
033@GwtIncompatible
034@ElementTypesAreNonnullByDefault
035public abstract class ForwardingLoadingCache<K, V> extends ForwardingCache<K, V>
036    implements LoadingCache<K, V> {
037
038  /** Constructor for use by subclasses. */
039  protected ForwardingLoadingCache() {}
040
041  @Override
042  protected abstract LoadingCache<K, V> delegate();
043
044  @Override
045  public V get(K key) throws ExecutionException {
046    return delegate().get(key);
047  }
048
049  @Override
050  public V getUnchecked(K key) {
051    return delegate().getUnchecked(key);
052  }
053
054  @Override
055  public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
056    return delegate().getAll(keys);
057  }
058
059  @Override
060  public V apply(K key) {
061    return delegate().apply(key);
062  }
063
064  @Override
065  public void refresh(K key) {
066    delegate().refresh(key);
067  }
068
069  /**
070   * A simplified version of {@link ForwardingLoadingCache} where subclasses can pass in an already
071   * constructed {@link LoadingCache} as the delegate.
072   *
073   * @since 10.0
074   */
075  public abstract static class SimpleForwardingLoadingCache<K, V>
076      extends ForwardingLoadingCache<K, V> {
077    private final LoadingCache<K, V> delegate;
078
079    protected SimpleForwardingLoadingCache(LoadingCache<K, V> delegate) {
080      this.delegate = Preconditions.checkNotNull(delegate);
081    }
082
083    @Override
084    protected final LoadingCache<K, V> delegate() {
085      return delegate;
086    }
087  }
088}