摆脱邪恶的单身人士
TL;DR:重构单例以减少耦合
public class DatabaseConnection { private static DatabaseConnection instance; private DatabaseConnection() {} public static DatabaseConnection getInstance() { if (instance == null) { instance = new DatabaseConnection(); } return instance; } public void connect() { } } public class Service { public void performTask() { DatabaseConnection connection = DatabaseConnection.getInstance(); connection.connect(); } }
public class DatabaseConnection { // 1. Identify the singleton public void connect() { } } public class Service { // 2. Locate all references to its getInstance() method. private DatabaseConnection connection; // 3. Refactor the singleton to a standard class. public Service(DatabaseConnection connection) { // 4. Inject it as a dependency. this.connection = connection; } public void performTask() { connection.connect(); } } DatabaseConnection connection = new DatabaseConnection(); // You can also mock the connection in your tests Service service = new Service(connection); service.performTask();
[X] 半自动
当您更新对单例的所有引用并正确处理其依赖项时,此重构是安全的。
测试每个步骤可确保不会遗漏对单例的引用。
远离单例的重构使代码更加模块化、可测试,并且不太容易出现由全局状态引起的问题。
注入依赖项使您可以在测试和其他上下文中轻松地将 DatabaseConnection 替换为模拟或不同的实现。
图片由 PublicDomainPictures 在 Pixabay上
本文是重构系列的一部分。
以上是重构——替换单例的详细内容。更多信息请关注PHP中文网其他相关文章!