bowling-analysis-system
Version:
A comprehensive system for analyzing bowling techniques using video processing and metrics calculation
114 lines (101 loc) • 2.8 kB
JavaScript
/**
* @fileoverview Service Container for dependency injection
* @module core/ServiceContainer
*/
/**
* Service Container for dependency injection
*/
class ServiceContainer {
/**
* Create a new service container
*/
constructor() {
this.services = new Map();
this.instances = new Map();
}
/**
* Register a service factory
* @param {string} name - Service name
* @param {Function} factory - Service factory function
* @param {Object} options - Registration options
* @returns {ServiceContainer} Container instance for chaining
*/
singleton(name, factory, options = {}) {
this.services.set(name, {
factory,
options,
singleton: true
});
return this;
}
/**
* Register a service factory that creates a new instance each time
* @param {string} name - Service name
* @param {Function} factory - Service factory function
* @param {Object} options - Registration options
* @returns {ServiceContainer} Container instance for chaining
*/
transient(name, factory, options = {}) {
this.services.set(name, {
factory,
options,
singleton: false
});
return this;
}
/**
* Register an instance
* @param {string} name - Service name
* @param {Object} instance - Service instance
* @returns {ServiceContainer} Container instance for chaining
*/
instance(name, instance) {
this.instances.set(name, instance);
return this;
}
/**
* Get a service
* @param {string} name - Service name
* @returns {Object} Service instance
*/
get(name) {
// Return existing instance if available
if (this.instances.has(name)) {
return this.instances.get(name);
}
// Check if service is registered
if (!this.services.has(name)) {
throw new Error(`Service not registered: ${name}`);
}
const service = this.services.get(name);
const instance = service.factory();
// Store instance if singleton
if (service.singleton) {
this.instances.set(name, instance);
}
return instance;
}
/**
* Check if a service is registered
* @param {string} name - Service name
* @returns {boolean} Whether the service is registered
*/
has(name) {
return this.services.has(name) || this.instances.has(name);
}
/**
* Remove a service
* @param {string} name - Service name
* @returns {boolean} Whether the service was removed
*/
remove(name) {
this.instances.delete(name);
return this.services.delete(name);
}
}
// Create default container
const defaultContainer = new ServiceContainer();
module.exports = {
ServiceContainer,
defaultContainer
};