Burak Aktas Software Engineer

Adapter Design Pattern in Java

Adapter design pattern is a structural design pattern that provides two unrelated interfaces to work together. The most common illustration about adapter design pattern is sockets from different countries. Well most of us faced with laptop adapter issues when traveling, and looked for appropriate adapter for our laptops. So, by using an adapter we are able to plug our laptop chargers to sockets. Or using a card reader to plug our memory card from our camera to our computer. Thus, we make two unrelated interfaces to work together. The elements of adapter design pattern are Client, Target, Adapter and Adaptee. We can see the Gang of Four definition for ADP, and description of each element of it below;

Convert the interface of class into another interface clients expect.Adapter lets class work together that couldn’t otherwise because of incompatible interfaces.

Create Qualifiers for CDI Beans

As I described in my previous post, we can define and inject cdi beans by @Named annotation. Well according to the CDI specification (JSR-299) injecting beans by their names is legacy and tend to cause issues (if a bean is tried to be injected by an undefined/wrong name then we will get errors which are hard to find). Thus, we are going to create different annotations (qualifiers) to inject different type of beans from same interface. Moreover, we will use Weld CDI implementation.

Convert objects to/from JSON by Jackson example

We will see a simple example about converting objects to/from JSON objects in Java by Jackson. First, add maven dependency for jackson.


Arquillian Example for CDI Dependency Injection

Arquillian is a platform which provides integration tests by deploying, running containers so that we can easily use cdi beans in tests. In this tutorial we will see how to inject and use cdi beans in test classes by running Arquillian.

As a first step we have to add Arquillian core library in our pom.xml in the dependencyManagement block. Well it is completely optional, and you can add it in dependencies section.

Java CDI Dependency Injection Example

CDI (Context and Dependency Injection) is a specification defined in JSR-299. Major aim is loose coupling by dependency injection.In this tutorial we will see how to use CDI Dependency Injection in java with three different ways;

  • Field injection
  • Constructor injection
  • Setter method injection