Design Patterns: Service Locator

Please see my other Design Pattern articles.

Completing the IoC Design Pattern.

0-pattern-service-locator-strongly-typed

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.

1-pattern-service-locator-strongly-typed

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.

2-pattern-service-locator-strongly-typed

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.

3-pattern-service-locator-strongly-typed

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().

4-pattern-service-locator-strongly-typed

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s