Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of factory classes in Java

I have used Java for quite a long time, but I never did find out, what makes factories so special. Can somebody please explain it to me? Is there any reason why I should want to implement my own factory (if it's even possible)?

like image 355
Martin Dvoracek Avatar asked May 13 '13 20:05

Martin Dvoracek


2 Answers

Factory Patterns are fantastic for decoupling classes. For example, let's assume a common interface, Animal, and some classes that implement it. Dog, Cat.

If you do not know what the user will want to generate at run time, then you can not create a Dog pointer. It simply won't work!

What you can do though, is port that to a separate class, and at run time, pass a discriminator to the factory class. The class will then return the object. For example:

public Animal getInstance(String discriminator)
{
    if(discriminator.equals("Dog")) {
         return new Dog();
    }
    // etc.
}

And the calling class simply uses:

String type = "Dog";
Animal value = Factory.getInstance(type);

This makes code extremely readable, separates decision logic from the logic performed on the value and decouples the classes via some common interface. All in all, pretty nice pattern!

like image 176
Tel Bouqi Avatar answered Sep 20 '22 20:09

Tel Bouqi


IMO the biggest benefits of Factory classes are configuration and data encapsulation. API design is perhaps the most common scenario where such classes come in really handy.

By offering developers Factory classes instead of direct access, I have a way to easily preventing from someone messing up with the internals of my API, for instance. Through Factory classes I also control how much you know about my infrastructure. If I don't want to tell you everything about how I provide a service internally, I will give you a Factory class instead.

For reliability and uniform design purposes, the most crucial internals should be enclosed in Factory classes.

They are a way to make sure that a random developer that comes along will not:

  • Break internals
  • Gain unwanted privileges
  • Break configuration formats
like image 25
flavian Avatar answered Sep 20 '22 20:09

flavian