java - Is this code implements 'Factory Pattern', factory methods, both or none? -
although subject has been discussed many times, still find myself confused it.
i have simple code sample:
public class fruitfactory { public static apple getapple() { return new apple(); } public static banana getbanana() { return new banana(); } public static orange getorange() { return new orange(); } }
- which
factory
type code is? , proper writing offactory methods
? - the factory pattern definition is: create object without exposing creation logic client
if expose client of creation complexity example below, bad factory implementation?
public static orange getorange(string weight, string size,) { return new orange(weight, size); }
as said, factory merely abstraction object creation implementation intentionally encapsulated behind factory's public interface. factory not have class, not have package -- different languages achieve encapsulation of state , behavioral details differently (consider closures, instance).
a function in language allows "top-level" functions, can factory well:
public orange growneworange(string weight, string size) { /// ...traditionally not callers concern. }
if factory hides creation code behind way use without concerning said creation code each created object, have useful isolation (between getting new objects , manages them) solves problem factory pattern designed solve.
there factories designed create , manage 1 kind of objects , there create , manage multiple kinds of objects. fruit factory can specify concrete class of fruit want, still matches valid factory pattern.
categorizing factory implementations "types" done various oop authors, , may useful various reasons, not essential able utilize general idea advantage.
the useful advice encapsulate creation code in java package or class, specifying parameters of created object done on per-object basis, while factory state controlling creation logic -- instance size of reused object pool etc -- set during factory creation itself. object pools 1 of examples of factory pattern @ work.
Comments
Post a Comment