0%

设计模式 | 反射工厂

通过反射和配置来实现工厂方法,达到解耦和的效果。这也是 springbean 工厂原理 spring | ApplicationContext 功能详解

创建一个文件 application.properties

1
UserServiceImpl=com.redisc.UserServiceImpl

然后实现

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
interface UserService {
void proc();
}

class UserServiceImpl implements UserService {

@Override
public void proc() {
System.out.println("UserServiceImpl 123");
}
}

class UserServiceFactory {
private static Properties env = new Properties();

static {
InputStream inputStream = Run.class.getResourceAsStream("/application.properties");
try {
env.load(inputStream);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static UserService getUserService() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
String userServiceImplPath = env.getProperty("UserServiceImpl");
UserService userService = (UserService) Class.forName(userServiceImplPath).newInstance();
return userService;
}
}

UserServiceFactory 通过读取配置的方式,来反射创建实例。

请我喝杯咖啡吧~