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
  • Certification
  • Compete
  • Career Fair
  • Hiring developers?
  1. Practice
  2. Java
  3. Advanced
  4. Java Factory Pattern
  5. Discussions

Java Factory Pattern

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 79 Discussions, By:

votes

Please Login in order to post a comment

  • tao_zhang 5 years ago+ 0 comments
    switch (order){
         case "pizza": return new Pizza();
         case "cake" : return new Cake();
         default : return null;
    }
    
    22|
    Permalink
  • sivaraam 4 years ago+ 0 comments
    return(order.equals("pizza"))?new Pizza():new Cake();
    
    14|
    Permalink
  • deiby1986 5 years ago+ 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;

    6|
    Permalink
  • dbmxer 3 years ago+ 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();
    
    5|
    Permalink
  • d_silva 2 years ago+ 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;
    
    2|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature