使用map实现注入依赖
时间: 2024-09-18 10:01:02 浏览: 53
在软件工程中,特别是使用依赖注入(Dependency Injection, DI)设计模式时,Map可以作为一种常见的容器来存储和管理对象及其依赖关系。Map通常用于将接口或类型名映射到具体的实现类。这里是一个简单的例子:
```java
// 定义接口和它的实现类
interface MyService {
void doSomething();
}
class ConcreteServiceA implements MyService {
@Override
public void doSomething() {
System.out.println("Doing something with A");
}
}
class ConcreteServiceB implements MyService {
@Override
public void doSomething() {
System.out.println("Doing something with B");
}
}
// 使用Map进行依赖注入
Map<String, MyService> serviceRegistry = new HashMap<>();
serviceRegistry.put("serviceA", new ConcreteServiceA());
serviceRegistry.put("serviceB", new ConcreteServiceB());
// 在需要的地方通过键获取并调用服务
MyService myService = serviceRegistry.get("serviceA"); // 获取ConcreteServiceA实例
myService.doSomething(); // 输出 "Doing something with A"
阅读全文
相关推荐



















