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