java - Is the Factory Method Pattern more flexible than Simple Factory? -



java - Is the Factory Method Pattern more flexible than Simple Factory? -

i've been reading book head first: design patterns, have found introduction design patterns. however, i've got question claim create in chapter 4:

they define "simple factory" pattern follows (java pseudocode):

public abstract class product { // product characteristics // concrete products should subclass } public class simplefactory { public product createproduct(){ // homecoming instance of subclass of product } } public class store { simplefactory factory; public product orderproduct(){ product product = factory.createproduct(); // manipulation on product homecoming product; } }

the "factory method" defined follows (class product remains same , omitted):

public abstract class store { //concrete stores must subclass , override createproduct() public abstract product createproduct(); public product orderproduct(){ product product = createproduct(); // manipulation on product homecoming product; } }

then authors go on claim mill method pattern much more flexible simple factory, because while simple mill "a 1 shot deal, mill method creating framework lets subclasses decide implementation should used" (page 135).

now don't why true. way see it, simple mill is, in senses, more flexible mill method: can subclass simple mill (instead of subclassing store) same behavior. can alter behavior @ runtime if wish! disadvantage of simple mill think of when product creation depends on state variables of store class: authors calling flexibility, or missing something?

you absolutely right: author's assumption has been not going subclass simplefactory, not fair assumption create (unless simplefactory marked final).

since simplefactory not final, can subclass it, gaining more flexibility mill method, because simplefactory replaces inheritance composition.

an improve approach making simplefactory interface. doing allow pick composition or inheritance according preference, because interface not limit in cases when store class inherits class.

public interface simplefactory { product createproduct(); }

then can utilize either composition

public class factoryimpl implements simplefactory { public product createproduct(){ // homecoming instance of subclass of product } } public class storecomposition { simplefactory mill = new factoryimpl(); }

or inheritance/composition combo

public class storeinheritance implements simplefactory { simplefactory mill = this; public product createproduct(){ // homecoming instance of subclass of product } }

java design-patterns factory factory-pattern

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -