Design Patterns: Service Locator

Please see my other Design Pattern articles.

Completing the IoC Design Pattern.


In my Design Patterns: Inversion of Control article, I illustrated how to decouple classes from having dependencies – the CustomerPayment class contained a dependency on the IPayment interface. Any class which has intimate knowledge of another is tightly-coupled to that class.
By implementing the IoC pattern, you provide for greater flexibility within an API.
In this article I will demonstrate one of two ways to complete the IoC pattern – using a strongly-typed Service Locator design pattern to move the creation of dependencies outside of the consuming class.

Since I’m beginning where the other article left off, I’ll begin with the central class – CustomerPayment, except I’ve designed to duplicate and renamed it to CustomerPaymentSLST.
The first thing you’ll notice that when compared its prior version, instead of containing an IPayment object (dependency), the constructor now receives an interface object – IPaymentServiceStronglyTyped.


Instead of having the implementation decide which behavior to use (tightly-coupled), I’ve abstracted it to a new interface so that another class may decide which behavior to implement.


Now I’ll create a new class in which the decision on which type of behavior is implemented.
Instead of having this choice where in the CustomerPaymentSLST class, now that I’ve moved it here the other class doesn’t have to care how a payment is made. If the type of payment changes, it’s changed here and it’s abstracted from the rest of the API. Currently, it’s still using PayInvoice class, but that may now easily be changed.


Now I may implement my behavior by first using my new interface which is then passed into the class of which I wish to call PayCustomerInvoice().


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s