design patterns - Purpose of factory classes in Java -


i have used java quite long time, never did find out, makes factories special. can please explain me? there reason why should want implement own factory (if it's possible)?

factory patterns fantastic decoupling classes. example, let's assume common interface, animal, , classes implement it. dog, cat.

if not know user want generate @ run time, can not create dog pointer. won't work!

what can though, port separate class, , @ run time, pass discriminator factory class. class return object. example:

public animal getinstance(string discriminator) {     if(discriminator.equals("dog")) {          return new dog();     }     // etc. } 

and calling class uses:

string type = "dog"; animal value = factory.getinstance(type); 

this makes code extremely readable, separates decision logic logic performed on value , decouples classes via common interface. in all, pretty nice pattern!


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -