1 /* 2 * Copyright (C) 2014 The Dagger Authors. 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 package dagger.internal; 18 19 import static dagger.internal.Preconditions.checkNotNull; 20 21 import dagger.Lazy; 22 23 /** 24 * A {@link Factory} implementation that returns a single instance for all invocations of {@link 25 * #get}. 26 * 27 * <p>Note that while this is a {@link Factory} implementation, and thus unscoped, each call to 28 * {@link #get} will always return the same instance. As such, any scoping applied to this factory 29 * is redundant and unnecessary. However, using this with {@link DoubleCheck#provider} is valid and 30 * may be desired for testing or contractual guarantees. 31 */ 32 public final class InstanceFactory<T> implements Factory<T>, Lazy<T> { create(T instance)33 public static <T> Factory<T> create(T instance) { 34 return new InstanceFactory<T>(checkNotNull(instance, "instance cannot be null")); 35 } 36 createNullable(T instance)37 public static <T> Factory<T> createNullable(T instance) { 38 return instance == null 39 ? InstanceFactory.<T>nullInstanceFactory() 40 : new InstanceFactory<T>(instance); 41 } 42 43 @SuppressWarnings("unchecked") // bivariant implementation nullInstanceFactory()44 private static <T> InstanceFactory<T> nullInstanceFactory() { 45 return (InstanceFactory<T>) NULL_INSTANCE_FACTORY; 46 } 47 48 private static final InstanceFactory<Object> NULL_INSTANCE_FACTORY = 49 new InstanceFactory<Object>(null); 50 51 private final T instance; 52 InstanceFactory(T instance)53 private InstanceFactory(T instance) { 54 this.instance = instance; 55 } 56 57 @Override get()58 public T get() { 59 return instance; 60 } 61 } 62