We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Practice
- Java
- Advanced
- Java Factory Pattern
- Discussions
Java Factory Pattern
Java Factory Pattern
tao_zhang + 0 comments switch (order){ case "pizza": return new Pizza(); case "cake" : return new Cake(); default : return null; }
sivaraam + 0 comments return(order.equals("pizza"))?new Pizza():new Cake();
deiby1986 + 0 comments If this is java Factory then we must use Java Factory:
Food demo = null; try{ order=order.substring(0, 1).toUpperCase() + order.substring(1); Class clazz = Class.forName(order); demo = (Food) clazz.newInstance(); }catch(Exception e){
}
return demo;
dbmxer + 0 comments Working off @m_hr1 and over engineering for fun...
try{ return (Food)FoodFactory.class.getClassLoader().loadClass(camelCase(order)).newInstance(); } catch ( Exception e ) { return null; } } private String camelCase(String name){ return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
d_silva + 0 comments I opted this way, to avoid a hard coded solution:
if (Pizza.class.getName().equalsIgnoreCase(order)){ return new Pizza(); } if (Cake.class.getName().equalsIgnoreCase(order)){ return new Cake(); } return null;
Load more conversations
Sort 79 Discussions, By:
Please Login in order to post a comment