擺脫邪惡的單身人士
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中文網其他相關文章!