ScriptsLab
WikiDownloadsSourcesSupport
ScriptsLab
DocumentationDownloadsGitHubDiscord

© 2026 ScriptsLab

Back to src/main/java/com/scriptslab/core/di
J

Container.java

Java · 160 lines · 4.3 KB

src/main/java/com/scriptslab/core/di/Container.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package com.scriptslab.core.di;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.logging.Logger;

/**
 * Lightweight dependency injection container.
 * Thread-safe singleton implementation.
 */
public final class Container {
    
    private static volatile Container instance;
    private static final Object LOCK = new Object();
    
    private final Map<Class<?>, Object> singletons;
    private final Map<Class<?>, Supplier<?>> factories;
    private final Logger logger;
    
    private Container() {
        this.singletons = new ConcurrentHashMap<>();
        this.factories = new ConcurrentHashMap<>();
        this.logger = Logger.getLogger("DI-Container");
    }
    
    /**
     * Gets the singleton instance of the container.
     * Double-checked locking for thread safety.
     * 
     * @return container instance
     */
    public static Container getInstance() {
        if (instance == null) {
            synchronized (LOCK) {
                if (instance == null) {
                    instance = new Container();
                }
            }
        }
        return instance;
    }
    
    /**
     * Registers a singleton instance.
     * 
     * @param type service type
     * @param instance service instance
     * @param <T> type parameter
     */
    public <T> void registerSingleton(Class<T> type, T instance) {
        if (type == null || instance == null) {
            throw new IllegalArgumentException("Type and instance cannot be null");
        }
        
        singletons.put(type, instance);
        logger.fine("Registered singleton: " + type.getSimpleName());
    }
    
    /**
     * Registers a factory for creating instances.
     * 
     * @param type service type
     * @param factory factory supplier
     * @param <T> type parameter
     */
    public <T> void registerFactory(Class<T> type, Supplier<T> factory) {
        if (type == null || factory == null) {
            throw new IllegalArgumentException("Type and factory cannot be null");
        }
        
        factories.put(type, factory);
        logger.fine("Registered factory: " + type.getSimpleName());
    }
    
    /**
     * Resolves a service by type.
     * First checks singletons, then factories.
     * 
     * @param type service type
     * @param <T> type parameter
     * @return optional containing service if found
     */
    @SuppressWarnings("unchecked")
    public <T> Optional<T> resolve(Class<T> type) {
        if (type == null) {
            return Optional.empty();
        }
        
        // Check singletons first
        Object singleton = singletons.get(type);
        if (singleton != null) {
            return Optional.of((T) singleton);
        }
        
        // Try factory
        Supplier<?> factory = factories.get(type);
        if (factory != null) {
            return Optional.of((T) factory.get());
        }
        
        return Optional.empty();
    }
    
    /**
     * Resolves a service or throws exception if not found.
     * 
     * @param type service type
     * @param <T> type parameter
     * @return service instance
     * @throws IllegalStateException if service not found
     */
    public <T> T resolveOrThrow(Class<T> type) {
        return resolve(type)
                .orElseThrow(() -> new IllegalStateException(
                        "Service not registered: " + type.getSimpleName()));
    }
    
    /**
     * Checks if a service is registered.
     * 
     * @param type service type
     * @return true if registered
     */
    public boolean isRegistered(Class<?> type) {
        return singletons.containsKey(type) || factories.containsKey(type);
    }
    
    /**
     * Unregisters a service.
     * 
     * @param type service type
     */
    public void unregister(Class<?> type) {
        singletons.remove(type);
        factories.remove(type);
        logger.fine("Unregistered: " + type.getSimpleName());
    }
    
    /**
     * Clears all registrations.
     * Use with caution!
     */
    public void clear() {
        singletons.clear();
        factories.clear();
        logger.info("Container cleared");
    }
    
    /**
     * Gets the number of registered services.
     * 
     * @return service count
     */
    public int size() {
        return singletons.size() + factories.size();
    }
}