Reputation: 165
When learning Facade design pattern, everywhere I find this kind of examples:
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 doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.
Upvotes: 3
Views: 702
Reputation: 954
Facade patterns, hides the complexity of the system and provides an interface to the client from where the client can access the system.
Typical example is compiler while as a client you can invoke compile method, but you don't see internal steps like scanning, parsing, ...
Upvotes: 0
Reputation: 3900
In a way you wrote your example, yes it will tightly couple your code. Mainly due to new
keyword which acts like a glue
to your dependencies.
Keep in mind that Facade pattern will not prevent you from creating tightly coupled dependencies or code. Main purpose of using it is to make your software component easier to use, more readable and maintainable and last but not least more testable.
If you want to avoid tightly 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
}
In that way you ensured that your Facade does not depend upon implementation, rather it depends upon abstraction. You'll be able to pass any implementation which implements ISystemA
or ISystemB
intefaces.
I suggest you to read more about Dependency Injection and containers which will greatly help you to wrap up classes' dependency graphs and automate constructor injection in that classes.
Upvotes: 4