」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在代碼中重構朋友依賴性?

如何在代碼中重構朋友依賴性?

發佈於2025-03-04
瀏覽:605

How to Refactor a Friend Dependency in Your Code? 
friend依賴性刪除重構

在軟件開發領域,朋友聲明可以引入緊密的耦合和維護問題。 This guide provides a detailed roadmap for refactoring a friend dependency properly, transforming your codebase into a more maintainable and resilient structure.

Unveiling the Need for Refactoring

Consider the following scenario: ClassA and ClassAAccessor share a friend dependency, granting ClassAAccessor access to protected members of ClassA.雖然這看起來很方便,但它帶來了幾個缺點:

UML 2.2已將朋友刻板印象置換為刻板印象。

Refactoring Step-by-Step

  • Step 1: Introduce an Abstract Interface
  • Replace the friend declaration with a class interface called InternalInterface, splitting the friend relationship into a direct dependency and a call dependency on InternalInterface.

Step 2: Move Operations to the Interface

Identify the operations constituting the call dependency and move them from ClassA to InternalInterface, extending InternalInterface with a protected constructor and marking ClassA's generalization association to InternalInterface as protected.

Step 3: Connect the組件

ClassaAccessor需要對InternalInterface的引用。在classa中實現附加方法,即actactAccessor(),並使用setInternalInternInterFaceref()將其引用到ClastaAccessor。當調用Classa :: actacta :: actactaAccessor()。 班級classaaccessor { 民眾: ClassaAccessor(Classa&Classa); void setInternalInterfaceRef(內部接口和newValue); 私人的: 內部接口* internalterfaceref; }; //將引用引用到Internalterface的方法 classa :: actactaccessor(ClassaAccessor&Conscontor){ consector.setInternal Interfaceref(*this); }

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3