AbstractModule.java
01 /*
02  * SPDX-License-Identifier: Apache-2.0
03  *
04  * Copyright 2008-2017 the original author or authors.
05  *
06  * Licensed under the Apache License, Version 2.0 (the "License");
07  * you may not use this file except in compliance with the License.
08  * You may obtain a copy of the License at
09  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package org.codehaus.griffon.runtime.core.injection;
19 
20 import griffon.core.injection.Binding;
21 import griffon.core.injection.Module;
22 
23 import javax.annotation.Nonnull;
24 import java.util.ArrayList;
25 import java.util.List;
26 
27 import static griffon.util.GriffonClassUtils.requireState;
28 import static java.util.Objects.requireNonNull;
29 
30 /**
31  @author Andres Almiray
32  @since 2.0.0
33  */
34 public abstract class AbstractModule implements Module {
35     protected final List<Binding<?>> bindings = new ArrayList<>();
36     protected BindingBuilder<?> currentBinding;
37     protected boolean configured;
38 
39     public final void configure() {
40         requireState(!configured, "Module " this " has already been configured");
41         doConfigure();
42         configured = true;
43     }
44 
45     protected abstract void doConfigure();
46 
47     @Nonnull
48     @Override
49     public final List<Binding<?>> getBindings() {
50         if (!configured) {
51             configure();
52         }
53 
54         if (currentBinding != null) {
55             bindings.add(currentBinding.getBinding());
56             currentBinding = null;
57         }
58         return bindings;
59     }
60 
61     protected <T> AnnotatedBindingBuilder<T> bind(@Nonnull Class<T> clazz) {
62         requireNonNull(clazz, "Argument 'class' must not be null");
63         if (currentBinding != null) {
64             bindings.add(currentBinding.getBinding());
65         }
66 
67         AnnotatedBindingBuilder<T> builder = Bindings.bind(clazz);
68         currentBinding = builder;
69         return builder;
70     }
71 }