Skip to main content
Glama
apolosan

Design Patterns MCP Server

by apolosan
dependency-injection.json4.54 kB
{ "id": "dependency-injection", "name": "Dependency Injection", "category": "Creational", "description": "A class accepts the objects it requires from an injector instead of creating the objects directly", "when_to_use": "Loose coupling\nTestability\nModular architecture\nConfiguration management", "benefits": "Loose coupling\nEasy testing\nConfiguration flexibility\nDependency management", "drawbacks": "Increased complexity\nLearning curve\nRuntime overhead", "use_cases": "Service containers\nFramework configuration\nUnit testing\nPlugin systems", "complexity": "Medium", "tags": ["creational", "dependency-injection", "inversion-of-control", "testability"], "examples": { "typescript": { "language": "typescript", "code": "// Dependency Injection Container\ninterface ServiceContainer {\n register<T>(token: symbol, factory: () => T): void;\n registerSingleton<T>(token: symbol, factory: () => T): void;\n get<T>(token: symbol): T;\n}\n\nclass SimpleContainer implements ServiceContainer {\n private services = new Map<symbol, () => any>();\n private singletons = new Map<symbol, any>();\n\n register<T>(token: symbol, factory: () => T): void {\n this.services.set(token, factory);\n }\n\n registerSingleton<T>(token: symbol, factory: () => T): void {\n this.register(token, () => {\n if (!this.singletons.has(token)) {\n this.singletons.set(token, factory());\n }\n return this.singletons.get(token);\n });\n }\n\n get<T>(token: symbol): T {\n const factory = this.services.get(token);\n if (!factory) {\n throw new Error(`Service not registered: ${token.toString()}`);\n }\n return factory();\n }\n}\n\n// Service tokens\nconst TOKENS = {\n DATABASE: Symbol('Database'),\n CACHE: Symbol('Cache'),\n LOGGER: Symbol('Logger')\n};\n\n// Services\ninterface Database {\n query(sql: string): Promise<any[]>;\n}\n\nclass PostgresDatabase implements Database {\n async query(sql: string): Promise<any[]> {\n // Implementation\n return [];\n }\n}\n\ninterface Cache {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n}\n\nclass RedisCache implements Cache {\n async get<T>(key: string): Promise<T | null> {\n // Implementation\n return null;\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n // Implementation\n }\n}\n\ninterface Logger {\n info(message: string): void;\n error(message: string): void;\n}\n\nclass ConsoleLogger implements Logger {\n info(message: string): void {\n console.log(`[INFO] ${message}`);\n }\n\n error(message: string): void {\n console.error(`[ERROR] ${message}`);\n }\n}\n\n// Service that depends on other services\nclass UserService {\n constructor(\n private db: Database,\n private cache: Cache,\n private logger: Logger\n ) {}\n\n async getUser(id: string) {\n this.logger.info(`Fetching user ${id}`);\n\n // Try cache first\n const cached = await this.cache.get(`user:${id}`);\n if (cached) {\n this.logger.info(`User ${id} found in cache`);\n return cached;\n }\n\n // Fetch from database\n const users = await this.db.query(`SELECT * FROM users WHERE id = $1`, [id]);\n if (users.length === 0) {\n throw new Error(`User ${id} not found`);\n }\n\n const user = users[0];\n\n // Cache the result\n await this.cache.set(`user:${id}`, user);\n\n this.logger.info(`User ${id} fetched from database`);\n return user;\n }\n}\n\n// Dependency injection setup\nconst container = new SimpleContainer();\n\n// Register services\ncontainer.registerSingleton(TOKENS.DATABASE, () => new PostgresDatabase());\ncontainer.registerSingleton(TOKENS.CACHE, () => new RedisCache());\ncontainer.registerSingleton(TOKENS.LOGGER, () => new ConsoleLogger());\n\n// Register UserService with its dependencies\ncontainer.register(TOKENS.USER_SERVICE, () => {\n const db = container.get<Database>(TOKENS.DATABASE);\n const cache = container.get<Cache>(TOKENS.CACHE);\n const logger = container.get<Logger>(TOKENS.LOGGER);\n return new UserService(db, cache, logger);\n});\n\n// Usage\nconst userService = container.get<UserService>(TOKENS.USER_SERVICE);\nconst user = await userService.getUser('123');\n\n// Benefits of DI:\n// 1. Easy testing - can inject mock services\n// 2. Loose coupling - services don't create dependencies\n// 3. Configuration flexibility - can swap implementations\n// 4. Dependency management - container handles lifecycle" } } }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/apolosan/design_patterns_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server