Skip to main content

Factory Pattern/ Google Guice - Java

Plan

Demonstrate Factory Design Pattern and show how Google Guice Dependency Injection library can be used as an alternative to automatically create object and inject it into other classes.

Program Description

Let us write a program to get a Computer. Computer can be of PC or MAC. After getting the computer, we start the computer and get its configuration details like RAM, Hard Disk and CPU. Program should allow for extending the computer types, that is to add more types like: LINUX, CHROMEBOOK etc.. with little or no code update in application.

How to run the program ?

  • Clone GitHub repository
    • git clone git@github.com:smarigowda/FactoryVersusGuiceDI.git
  • Open the project in Intellij IDE
  • Run the program which is using Factory Deisign Pattern - ClientUsingFactory

  • Run the program which is using Google Guice - ClientUsingGoogleGuiceDI

Factory Pattern

Sequence Diagram

How it works

  • Create a Computer Interface
  • Create a PC Class implementing Computer Interface
  • Create MAC Class implementing Computer Interface
  • Create a ComputerFactory with getComputer() method. This method will return either a PC or MAC depending on what the client asks for.
  • Create a Client (main program). Client asks the factory for a Computer (PC or MAC). Factory creates the Computer and gives it to the client
  • Client starts the Computer and gets the detail. Note that creation of Computer and the specific Computer details are abstracted for the Client. Client just knows the type of Computer to ask. This way the Client can deal with any type of computer without changing its code.
  • Adding a new type of Computer (ex: LINUX) is just adding another Class implementing the Computer Interface.

Google Guice Dependency Injection

Sequence Diagram

How it works

  • Google Guice provides an abstract class called AbstractModule. First create a class which extends AbstractModule and override the configure() method. Inside this method, add configuration to bind the Computer to PC or MAC
  • Client program gets an injector instance from Guice.
  • Using this injector instance, client gets an instance of application, runs the app, which in trun starts computer and gets computer details.
  • Note that Guice automatically creates an instance of Computer and gives it to Application

Pros and Cons of Dependency Injection

Pros

  • Loose coupling
  • Makes the code lean and clean
  • Makes unit testing of classes easy
  • Easy to maintain
  • Separates construction and wiring code from application code

Cons

  • It can slow down initialization

Notes

  • Dependency Injection frameworks are also referred to as IoC containers
  • Dependency Injector can be seen as a Service
  • Injector needs bootstraping
  • Once the injector is bootstrapped, we can obtain Objects from it
  • We can think of Guice as a Factory class