Java Layers Pattern – Using Interfaces in Layers

javalayersobject-oriented-design

I'm developing a Java software according to the object-oriented Layers architectural pattern. Every layer should be clearly separated from the rest, and provide a well-defined interface to use it's services (maybe more than one).

A common example for these layers could be an architecture consisting of a request processing layer, a business logic layer and a persistence layer.

However, I'm not sure how to use Java interfaces correctly to implement this structure. I guess that each layer should have it's own Java package. Should every layer contain one Java interface that defines methods to access it? Which classes implement these interfaces? Classes from the layer or classes from outside the layer? Which classes methods does an outside object use if it wants to use a layer?

Best Answer

The idea of the Layered Architecture is that each layer provides an abstraction to the previous layer, so a layer depends only on the previous layer. As an example with a Web Service

Request Management

public interface IXController {
    post();
    get();
    delete();
}

public class XControler implements IXController {
public XController (IXService service){}
    post(){}
    get(){}
    delete(){}
}

Business Layer

public interface IXSercice {
   doSomething(); 
}

public class XService implements IXService {
    public XService (IXDao dao){}
    doSomething(){}
}

Persistence layer

public interface IXDao {
    doSomething();
}

public class XDao implements IXDao {
    public XDao (){}
    doSomething(){}
}

As you may see the interfaces role is only to provide contracts between your layers, this can also be useful when using some patterns as Factory or Dependency injection.

Who access the interfaces? Whoever has a dependency on the object.

Everything else is solved with SOLID principles and OOP, and you should consider using design patterns.