題目描述

在這個題目中,您將會得到一個Food介面,Pizza類別和Cake類別會實作這個Food介面,它們都會擁有getType方法。



在Main類別的main方法中要產生出FoodFactory類別的物件實體,FoodFactory類別包含了一個getFood(String)物件方法,可以根據傳入的參數來回傳一個新的Pizza或是Cake類別的物件實體。

原題網址

https://www.hackerrank.com/challenges/java-factory

範例輸入1

cake

範例輸出1

The factory returned class Cake
Someone ordered a Dessert!

範例輸入2

pizza

範例輸出2

The factory returned class Pizza
Someone ordered Fast Food!

解題概念

實作FoodFactory類別的getFood方法,利用switch結構來判斷傳入的字串參數。如果傳入的字串為「pizza」,就產生出一個新的Pizza物件;如果傳入的字串為「cake」,就產生出一個新的Cake物件。

參考答案

import java.security.Permission;
import java.util.Scanner;

interface Food {

    public String getType();
}

class Pizza implements Food {

    @Override
    public String getType() {
        return "Someone ordered a Fast Food!";
    }
}

class Cake implements Food {

    @Override
    public String getType() {
        return "Someone ordered a Dessert!";
    }
}

class FoodFactory {

    public Food getFood(final String order) {
        switch (order.toLowerCase()) {
            case "pizza":
                return new Pizza();
            case "cake":
                return new Cake();
            default:
                return null;
        }
    }
}

public class Solution {

    public static void main(final String[] args) throws Exception {
        Do_Not_Terminate.forbidExit();

        try {
            final Scanner sc = new Scanner(System.in);
            final FoodFactory foodFactory = new FoodFactory();
            final Food food = foodFactory.getFood(sc.nextLine());
            System.out.println("The factory returned " + food.getClass());
            System.out.println(food.getType());
        } catch (Do_Not_Terminate.ExitTrappedException e) {
            System.out.println("Unsuccessful Termination!!");
        }
    }
}

class Do_Not_Terminate {

    public static class ExitTrappedException extends SecurityException {

        private static final long serialVersionUID = 1L;
    }

    public static void forbidExit() {
        final SecurityManager securityManager = new SecurityManager() {
            @Override
            public void checkPermission(final Permission permission) {
                if (permission.getName().contains("exitVM")) {
                    throw new ExitTrappedException();
                }
            }
        };
        System.setSecurityManager(securityManager);
    }
}