blob: 47285ccaf2fdf8b4ce1e7b910ea64d6dcdee9da6 [file] [log] [blame]
crazybobleea6e73982007-02-02 00:21:07 +00001/**
2 * Copyright (C) 2006 Google Inc.
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
17package com.google.inject;
18
crazybobleee3adfd62007-02-02 21:30:08 +000019import com.google.inject.util.ToStringBuilder;
20
crazybobleea6e73982007-02-02 00:21:07 +000021/**
22 * A binding from a {@link Key} (type and name) to an implementation.
23 *
24 * @author crazybob@google.com (Bob Lee)
25 */
26public class Binding<T> {
27
28 final ContainerImpl container;
29 final Key<T> key;
30 final Object source;
31 final InternalFactory<? extends T> internalFactory;
32
33 Binding(ContainerImpl container, Key<T> key,
34 Object source, InternalFactory<? extends T> internalFactory) {
35 this.container = container;
36 this.key = key;
37 this.source = source;
38 this.internalFactory = internalFactory;
39 }
40
41 /**
42 * Gets the key for this binding.
43 */
44 public Key<T> getKey() {
45 return key;
46 }
47
48 /**
49 * Gets the source object, an arbitrary object which points back to the
50 * configuration which resulted in this binding.
51 */
52 public Object getSource() {
53 return source;
54 }
55
56 volatile Factory<T> factory;
57
58 /**
crazyboblee2008ec72007-02-02 02:23:50 +000059 * Gets the factory which returns instances of {@code T}.
crazybobleea6e73982007-02-02 00:21:07 +000060 */
61 public Factory<T> getFactory() {
62 if (factory == null) {
63 factory = container.getFactory(key);
64 }
65 return factory;
66 }
67
68 InternalFactory<? extends T> getInternalFactory() {
69 return internalFactory;
70 }
71
72 static <T> Binding<T> newInstance(ContainerImpl container, Key<T> key,
73 Object source, InternalFactory<? extends T> internalFactory) {
74 return new Binding<T>(container, key, source, internalFactory);
75 }
76
77 /**
78 * Is this a constant binding?
79 */
80 public boolean isConstant() {
81 return internalFactory instanceof ConstantFactory<?>;
82 }
crazybobleee3adfd62007-02-02 21:30:08 +000083
84 public String toString() {
85 return new ToStringBuilder(Binding.class)
86 .add("key", key)
87 .add("source", source)
88 .add("factory", internalFactory)
89 .toString();
90 }
crazybobleea6e73982007-02-02 00:21:07 +000091}