3

I'm using this link as my basis link as The example given seemed simplest to start with from the other examples on the net. Can someone please explain why:

  1. I can understand the implementation and the interface codes. But why are they returning an interface?

  2. Also, while they're checking for string equals "jdbc", in both cases they return the same statements. This is where I get confused. Shouldn't they be returning different implementations of the same interface?

Thanks!

Community
  • 1
  • 1
chipmunk
  • 545
  • 2
  • 9
  • 18
  • They are not returning interface UserDAO , they are returning UserDAOImpl that implements the UserDAO interface and is a concrete class. – Mustafa sabir Jun 13 '14 at 13:35

1 Answers1

1
  1. The factory is returning an interface, so that it decouples the different implementations with the module that uses them.
    For example, if UserDAOImpl would, for some reason, change its name to UserDAOConcrete, you would only need to change the factory code, and nothing else, because everything else is using the interface (which didn't change)

  2. I guess the user is retuning the same implementaion just for a matter of simplicity, and because it is irrelevant to the question itself. The code is a sample. In reality, you would return a different implementation depending on the argument passed to the factory method. Please also note, that he may also have done it because, the last else is a default implementation in case the previous conditions didn't pass. The default implementation may be one that he is already returning with a different argument

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 2
    1. More importantly it allows you to have different DAO implementations, depending on context. For instance you might have a UserDaoJpa implemented using Hibernate, for your production software, and a UserDaoMock implemented using Mockito for your automated test suite. – Mikkel Løkke Jun 13 '14 at 14:51
  • Very important reason – Matias Cicero Jun 13 '14 at 14:52