java - Benefit of factory class over other polymorphism -
i'm trying figure out purpose of factory classes in java. everywhere says purpose is
- to create objects without exposing creation logic client
- to refer newly created object using common interface
examples show interface, e.g.
public interface shape { void draw(); }
with concrete classes implementing interface e.g.
public class circle implements shape { @override public void draw() { // draw circle } }
and factory, e.g.
public class shapefactory { public shape getshape(string shapetype){ if(shapetype.equalsignorecase("circle")){ return new circle(); } // implement other types of shape return null; } }
use of factory along lines of:
shape shape1 = shapefactory.getshape("circle");
my question is: how better using pure polymorphism without factory, e.g.:
shape shape1 = new circle();
it seems me achieves common interface factory. i'm not quite sure benefit of 'hiding creation logic' is, when seems creation logic of creating circle same creation logic of creating factory.
the main benefit of using factories offer form of abstraction greater typical inheritance can offer. example:
what factory produce object?
does allocate new object? access pool, conserve resources? using factory, it's possible 'new' keyword never used, saving memory and/or gc overhead. factory can perform actions constructor shouldn't do, such making remote proceedure calls, or accessing database. sometimes, factory return future instance, meaning doing actual processing in parallel thread!
where factory come from?
did implement factory yourself? import factory library? injected through form of ioc? http://en.wikipedia.org/wiki/inversion_of_control
is summary, factories used because pretty ultimate form of abstraction producing something
Comments
Post a Comment