HackerRank Java- Factory Pattern




In this problem, you are given an interface Food. There are two classes Pizza and Cake which implement the Food interface, and they both contain a method getType().

The main function in the Main class creates an instance of the FoodFactory class. The FoodFactory class contains a method getFood(String) that returns a new instance of Pizza or Cake according to its parameter.

You are given the partially completed code in the editor. Please complete the FoodFactory class.



  1. import java.util.*;
  2. import java.security.*;
  3. interface Food {
  4. public String getType();
  5. }
  6. class Pizza implements Food {
  7. public String getType() {
  8. return "Someone ordered a Fast Food!";
  9. }
  10. }
  11. class Cake implements Food {
  12. public String getType() {
  13. return "Someone ordered a Dessert!";
  14. }
  15. }
  16. class FoodFactory {
  17. public Food getFood(String order) {
  18. switch (order.toLowerCase()) {
  19. case "pizza":
  20. return new Pizza();
  21. case "cake":
  22. return new Cake();
  23. default:
  24. return null;
  25. }
  26. }//End of getFood method
  27. }//End of factory class
  28. public class Solution {
  29. public static void main(String args[]){
  30. Do_Not_Terminate.forbidExit();
  31. try{
  32. Scanner sc=new Scanner(System.in);
  33. //creating the factory
  34. FoodFactory foodFactory = new FoodFactory();
  35. //factory instantiates an object
  36. Food food = foodFactory.getFood(sc.nextLine());
  37. System.out.println("The factory returned "+food.getClass());
  38. System.out.println(food.getType());
  39. }
  40. catch (Do_Not_Terminate.ExitTrappedException e) {
  41. System.out.println("Unsuccessful Termination!!");
  42. }
  43. }
  44. }
  45. class Do_Not_Terminate {
  46. public static class ExitTrappedException extends SecurityException {
  47. private static final long serialVersionUID = 1L;
  48. }
  49. public static void forbidExit() {
  50. final SecurityManager securityManager = new SecurityManager() {
  51. @Override
  52. public void checkPermission(Permission permission) {
  53. if (permission.getName().contains("exitVM")) {
  54. throw new ExitTrappedException();
  55. }
  56. }
  57. };
  58. System.setSecurityManager(securityManager);
  59. }
  60. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube