Facade construction and tight coupling

When I study the facade design pattern, I find examples like this everywhere:

public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}

      

I don’t know if I’m wrong, but if it does not create a close relationship between the Facade class and systems (SystemA and SystemB), even if SystemA and SystemB inherit from some abstract class or interface.

+3


source to share


2 answers


In a sense, you wrote your example, yes, it will tie your code tightly. Mostly because of the keyword new

that acts like glue

for your dependencies.

Keep in mind that the Facade pattern doesn't stop you from writing tightly coupled dependencies or code. The main purpose of using it is to make your software component easier to use, more readable and maintainable, and, just as important, to test.

If you want to avoid tight coupling, you need to pass abstract dependencies in your Facade class:

public class Facade
{
 private readonly ISystemA subsystemA;
 private readonly ISystemB subsystemB;

 public Facade(ISystemA subsystemA, ISystemB subsystemB)
 {
    this.subsystemA = subsystemA;
    this.subsystemB = subsystemB;
 }

 public void CreateAccount()
 {      
   this.subsystemA.CreateCreditCard();
   this.subsystemB.CheckCreditCard();
 }
}

      



You need to create interfaces (or abstract classes):

public interface ISystemA
{
 void CreateCreditCard();
 //other methods here
}

public interface ISystemB
{
  void CheckCreditCard();
  //other methods here
}

      

This way, you ensured that your Facade is implementation independent, but abstraction dependent. You will be able to pass any implementation that implements ISystemA

or ISystemB

intefaces.

I suggest you read more about Dependency Injection and containers, which will greatly help you wrap class dependency graphs and automate constructor injection in those classes.

+4


source


Facade templates hide the complexity of the system and provide an interface for the client from which the client can access the system.
The compiler is a typical example, whereas as a client you can call the compilation method, but you don't see the internal steps like scanning, parsing, ...



0


source







All Articles