AbstractModule.java
01 /*
02  * Copyright 2008-2016 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
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 package org.codehaus.griffon.runtime.core.injection;
17 
18 import griffon.core.injection.Binding;
19 import griffon.core.injection.Module;
20 
21 import javax.annotation.Nonnull;
22 import java.util.ArrayList;
23 import java.util.List;
24 
25 import static griffon.util.GriffonClassUtils.requireState;
26 import static java.util.Objects.requireNonNull;
27 
28 /**
29  @author Andres Almiray
30  @since 2.0.0
31  */
32 public abstract class AbstractModule implements Module {
33     protected final List<Binding<?>> bindings = new ArrayList<>();
34     protected BindingBuilder<?> currentBinding;
35     protected boolean configured;
36 
37     public final void configure() {
38         requireState(!configured, "Module " this " has already been configured");
39         doConfigure();
40         configured = true;
41     }
42 
43     protected abstract void doConfigure();
44 
45     @Nonnull
46     @Override
47     public final List<Binding<?>> getBindings() {
48         if (!configured) {
49             configure();
50         }
51 
52         if (currentBinding != null) {
53             bindings.add(currentBinding.getBinding());
54             currentBinding = null;
55         }
56         return bindings;
57     }
58 
59     protected <T> AnnotatedBindingBuilder<T> bind(@Nonnull Class<T> clazz) {
60         requireNonNull(clazz, "Argument 'class' must not be null");
61         if (currentBinding != null) {
62             bindings.add(currentBinding.getBinding());
63         }
64 
65         AnnotatedBindingBuilder<T> builder = Bindings.bind(clazz);
66         currentBinding = builder;
67         return builder;
68     }
69 }