micho
micho

Reputation: 119

Java Factory Pattern with Enum


i have to use the factory pattern with singleton. My Factory Class creates two different objects depending on an enum type.

what is the best way to return the right object.

solution 1: by an if-else decision in the factory:

if(enumType == "objectA") return new objectA()

solution 2: the enum class has a return function:

enum ObjectType{ ObjectA{ .. return new ObjectA()..}}

thx, mike

Upvotes: 0

Views: 1887

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533730

If you can only have two instances of a class, I would use an Enum unless it need to have another class as a super-class.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272357

Write a function on the enum. That way you're not going to forget to add a clause to your factory method when you add a new enum.

As a rule, I'd favour polymorphism and method implementation over sequences of if/else if etc. for virtually any solution. It's much less error prone, and issues will be caught at compile time, not run time.

Upvotes: 7

Related Questions