Home > Article > Backend Development > How to Refactor a \"Friend\" Dependency Declaration: A Step-by-Step Guide to Removing Excessive Interdependency?
One may encounter a scenario where removing a "friend" dependency between two classes is desired, particularly due to concerns about excessive interdependency, maintenance issues, and outdated UML standards.
Extract the methods exposed by the "friend" class and create a new abstract interface. Establish a dependency relationship from the "friend" class to the interface and a "call" dependency from the other class to the interface.
Move the operations that make up the "call" dependency from the dependent class to the abstract interface. Make the interface extend a protected constructor for inheritance purposes and hide the protected generalization association between the dependent class and the interface.
In the final step, create a method in the "friend" class to pass a reference of the abstract interface to the dependent class. Call this method from the dependent class during initialization to establish the necessary connection.
ClassA (provider):
<code class="cpp">class ClassA : protected InternalInterface { public: attachAccessor(ClassAAccessor &accessor) { accessor.setInternalInterfaceRef(*this); } };</code>
ClassAAccessor (friend):
<code class="cpp">class ClassAAccessor { public: ClassAAccessor(ClassA& classA) : internalInterfaceRef(0) { classA.attachAccessor(*this); } private: InternalInterface* internalInterfaceRef; };</code>
The above is the detailed content of How to Refactor a \"Friend\" Dependency Declaration: A Step-by-Step Guide to Removing Excessive Interdependency?. For more information, please follow other related articles on the PHP Chinese website!