af86fe11281831a539f1a99dfa618fdfc3675c7c
[mdsal.git] / binding2 / mdsal-binding2-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / adapter / spi / builder / AdapterBuilder.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ClassToInstanceMap;
13 import com.google.common.collect.ImmutableClassToInstanceMap;
14 import com.google.common.collect.MutableClassToInstanceMap;
15 import java.util.Set;
16 import org.opendaylight.yangtools.concepts.Builder;
17
18 /**
19  * Class for building instances of delegates of specific type.
20  *
21  * @param <T>
22  *            - builded specific object type
23  * @param <D>
24  *            - delegates type
25  */
26 @Beta
27 public abstract class AdapterBuilder<T, D> implements Builder<T> {
28
29     private final ClassToInstanceMap<D> delegates = MutableClassToInstanceMap.create();
30
31     protected abstract T createInstance(ClassToInstanceMap<D> immutableDelegates);
32
33     /**
34      * Get required delegates.
35      *
36      * @return set of delegates
37      */
38     public abstract Set<? extends Class<? extends D>> getRequiredDelegates();
39
40     /**
41      * Add delegate to set of delegates.
42      *
43      * @param type
44      *            - type of delegate
45      * @param impl
46      *            - implementation of delegate
47      */
48     public final <V extends D> void addDelegate(final Class<V> type, final D impl) {
49         delegates.put(type, impl);
50     }
51
52     @Override
53     public final T build() {
54         checkAllRequiredServices();
55         return createInstance(ImmutableClassToInstanceMap.copyOf(delegates));
56     }
57
58     private void checkAllRequiredServices() {
59         for (final Class<? extends D> type : getRequiredDelegates()) {
60             Preconditions.checkState(delegates.get(type) != null, "Requires service %s is not defined.", type);
61         }
62     }
63 }