class PaymentFactory {
        // Provide access to the singleton instance.
    public static PaymentFactory getInstance(){
        return factory;
    }

        // Return a random instance of this class.
    public PaymentMethod randomPaymentMethod() {
        // Generate a random type and amount.
        final int num = (int) (Math.random() * 100.0);
        for(int i = 0; i < methods.length; i++){
            if(num < typePercentages[i]){
                return methods[i];
            }
        }
        throw new RuntimeException("Failure in PaymentMethod.randomInstance()");
    }

        // Prevent arbitrary creation.
    protected PaymentFactory(){
    }

        // A reference to the singleton for each PaymentMethod subclass.
    private final PaymentMethod[] methods = {
            Cash.getInstance(),
            Cheque.getInstance(),
            Credit.getInstance(),
    };

    // Cumulative percentage for each payment type
    //     Assert: typePercentages[typePercentages.length-1] == 100
    //     Assert: typePercentages.length == methods.length
    private static final int[] typePercentages = { 40, 60, 100 };

    // The singleton instance.
    private static final PaymentFactory factory = new PaymentFactory();
}
