2014-04-20

Guice Tutorial - 05 - Default interface implementation

Introduction

Sometimes we have to define interface and write only one class which implements it, for example we see possibility of extending in future or we want to make our class final to prohibit making subclasses of this type or maybe we want to have one default implementation of interface. This goal could be obtained with Guice.


Interface and class

We have class:
public class PdfReportWriter implements ReportWriter{
    @Override
    public void write() {
        // ...
    }
}
which implements our interface and it is only class which do this. Interface looks so:
@ImplementedBy(PdfReportWriter.class)
public interface ReportWriter {
    void write();
}
By the ImplementedBy annotation we say to Guice that if I ask for object of type ReportWriter than we should by default obtain object of type PdfReportWriter. Let's test it:
@Test
public void shouldGetImplementationOfInterface(){
    //given
    Injector sut = Guice.createInjector();
    //when
    ReportWriter reportWriter = sut.getInstance(ReportWriter.class);
    //then
    assertTrue(reportWriter instanceof PdfReportWriter);
}
And the test passes.


Conclusion

When we have interface which has only one implementation or we want to make this class default implementation for interface than we could use ImplementedBy annotation in Guice. Sources are available here.

No comments:

Post a Comment