Adapter and facade pattern
Created on: Sep 30, 2024
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
- This approach has the added advantage that we can use an adapter with any subclass of the adaptee.
- Pattern binds the client to an interface, not an implementation.
Real world use case:
- In a spring boot application, there are different handler to process incoming request. It can be like
HttpRequestHandlerAdapter,RequestMappingHandlerAdapter,SimpleControllerHandlerAdapter. For a rest api,RequestMappingHandlerAdapterwill get the particular adapter and invoke the method corresponding to it. By allowing different handler implementations to be processed through a common interface (HandlerAdapter), the design promotes flexibility, decoupling, and the ability to add new functionality without impacting existing code. - We can say that below program follows adapter program. if we have used
LinkedList, there will be a different type of iterator.
List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); Iterator<String> iterator = list.iterator();
- Spring data jpa provides a unified interface for accessing different database types (e.g., MySQL, PostgreSQL, MongoDB).
public interface UserRepository extends JpaRepository<User, Long> { List<User> findByLastName(String lastName); }
When to use
- When we are working with two incompatible systems or class or interface, the adapter pattern can be very powerful to use.
- Whenever we have several objects or methods doing something but have different implementations or different syntaxes, an adapter pattern can be definitely a good option!
Principle of Least Knowledge - talk only to your immediate friends. This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts. When you build a lot of dependencies between many classes, you are building a fragile system that will be costly to maintain and complex for others to understand.
The Facade Pattern enforces the Principle of Least Knowledge by limiting the client's interaction to just the facade. The client doesn't need to know about the internals of the subsystems that the facade manages. This leads to loose coupling between the client and the subsystems.
Facade pattern: The Facade Design Pattern is a structural design pattern that provides a simplified interface to a set of interfaces in a subsystem (a library, a framework, or any other complex set of classes), making it easier to use.
