Design Patterns: Adapter

Please see my other Design Pattern articles.

Exposing class behavior from another class.

0-pattern-adapter

Sometimes you might need to access and use functionality defined from one class from within your own class.

To illustrate this pattern, I’ll begin with a simple class that contains one method I wish to invoke from within my other class – this could be any class containing any behavior you wish to wrap and use from within your classes.

1-pattern-adapter

Creating an interface is the first step in implementing this pattern.
By defining the method(s) you wish to wrap in this interface, you will be able to expose it from other classes.

2-pattern-adapter

With my interface providing an interface (I know, bad pun) to the class containing the behavior I wish to expose, I now simply have to create my class from which to call the wrapped behavior.
First, I instantiate an object of the class whose behavior I was to implement and assign that object as a member of my class.
In the constructor, I assign the first class object to my class member.
Next, I’ll define methods to return the first class object and execute its behavior – this enables me to use the first class’ behavior.

3-pattern-adapter

Now I’m ready to utilize the pattern – use functionality from within my new class exposed from another class.

4-pattern-adapter

As you can see, the first class’ PublishArticle() method is available for me to use.

5-pattern-adapter

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