Java Factory Pattern

Sort by

recency

|

151 Discussions

|

  • + 0 comments

    my Code :

    import java.io.; import java.util.;

    interface Food {

    public String getType();
    

    }

    class Cake implements Food{ public String getType(){

        return"The factory returned class Cake\nSomeone ordered a Dessert!";
    }
    

    }

    class Pizza implements Food{ public String getType(){

        return"The factory returned class Pizza\nSomeone ordered a Fast Food!";
    }
    

    }

    public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
        Scanner s = new Scanner(System.in);
        String str =s.next();
        if(str.compareTo("cake") ==0){
            Food obj = new Cake();
        System.out.println(obj.getType());
    
        }
      if(str.compareTo("pizza") ==0){
          Food obj = new Pizza();
            System.out.println(obj.getType());
    
        }
    
    
    
    }
    

    }

  • + 0 comments

    return order.equals("cake") ? new Cake() : new Pizza();

  • + 0 comments

    Why on earth teach such bad habits on such a basic question. Where is the use of constants or enum?

  • + 0 comments

    If you're new and not seeing any of the prepopulated code, be sure to switch your language to an older version. Some new versions like Java 15 do not have the initial code. This is because Hackerrank is terrible.

  • + 0 comments

    Only one line of code

    return order.equalsIgnoreCase("Pizza") ? new Pizza() : new Cake();