java - Implementing Factory Method Pattern using Spring -
i want understand how following factory method pattern can implemented using spring.
here code without using spring
interface fileparser { void parse() } class xmlfileparser implements fileparser { void parse() { } } class pipefileparser implements fileparser { void parse() { } } class fileparserfactory { fileparser getparserinstance(string filetype) { if("xml".equals(filetype) return new xmlfileparer(); else return new pipefileparser(); } } class activityhandler() { void handle(string filetype) { fileparser fileparer = fileparserfactory.getparerinstance(filetype); fileparser.parse(); } }
thanks in advance.
i create bean fileparserfactory repsonsible returning new parsers. additionally factory bean have map (filetype => parser) , default parser
public class fileparserfactory { private map<string, fileparser> fileparsers; private fileparser defaultparser; fileparser getparserinstance(string filetype) { if(fileparsers.containskey(filetype)) return fileparsers.get(filetype); else return defaultparser; } public void setparsers(map<string, fileparser> parsers) { filepaarsers = parsers; } public void setdefaultparser(fileparser parser) { defaultparser = parser; } }
and in code:
@inject fileparserfactory factory;
...
factory.getparser(filetype);
i assume parsers may reused , thread safe.
this solution more generic , may extended if necessarry
Comments
Post a Comment