Idan Boadana
Idan Boadana

Reputation: 71

Adapter pattern without the use of interfaces

i'm trying to understand if the Adapter pattern implementation is dependent on interface realizations. from what i read, i should use adapter when i need to Convert the interface of a class into another interface clients expect.

i have been told the classic example of the 3 pronged plug using an adapter to connect to a two pronged plug...

so, from what i understand, if some method in a class has a method with a specific paramater signature, and i want to wrap it with logic that require more (or less) paramaters, then i should implement the adapter pattern.

from all the examples iv'e seen, the proper way to do this is to create an adapter class that realizes an interface with the desired method signature, and to hold the adoptee as a member in the adapter class. then, i can call the adpotee method through the realized interface method and input the logic.

the question is, if i only need to use one adoptee class, why use an interface? is it not simpler to drop the interface bit and just hold the adoptee as a member and implement the desired logic in a "stand alone" method?

is it required to realize an interface method here for the adapter pattern to be valid?

public class PostStatusAdapter
{
    public interface IpostStatus 
    { 
        void Post(string i_Post, string i_Password);
    }

    public class UserAdapter : IpostStatus
    {
        User Adoptee = new User();

        void IpostStatus.Post(string i_Post, string i_Password)
        {
            if (PasswordCorrect(i_Password))
            {
                Adoptee.PostStatus(i_Post);
            }
        }

        private bool PasswordCorrect(string i_Password) { ... }
    }
}

Upvotes: 2

Views: 604

Answers (1)

Thomas W
Thomas W

Reputation: 14164

Yes, essentially it's an Adapter if it implements an "external" interface or abstract API -- regardless of whether the "internal" connection is formalized as an interface or abstract API.

So it's still an Adapter when it hooks onto a specific internal implementation, which can fulfill/ answer the contract & methods of the external interface.

It may no longer be an Adapter if you implement significant logic within the Adapter itself -- then it probably becomes a Delegate.

Delegates implement functionality both themselves & especially by delegating to a referenced object.

Upvotes: 2

Related Questions