问题描述:

I wrote a GUI for users to input his/her credit card number. The program must return the correct Credit Card class subclass such as MasterCard, Visa, etc.

Here is my code:

abstract class CreditCard{

String cardNumber;

public CreditCard(String number) {

cardNumber = number;

}

}

All of my subclass such as MasterCard, Visa, etc extends the CreditCard superclass.

Example of one of my subclass:

class MasterCC extends CreditCard {

public MasterCC(String number) {

super(number);

}

}

I chose a Factory Design Pattern

class CreditCardFactory {

static CreditCard createCard(String number) {

CreditCard cc = null;

if (number.length() == 0 || number.length() > 19)

return cc;

else if (isMasterCard(number))

cc = new MasterCC(number);

else if (isVisa(number))

cc = new VisaCC(number);

else if (isAmericanExpress(number))

cc = new AmExCC(number);

else if (isDiscover(number))

cc = new DiscoverCC(number);

return cc;

}

private static boolean isMasterCard(String number){

if (number.length() != 16)

return false;

return (number.charAt(0) == '5'

&& 1 >= Integer.valueOf(number.charAt(1))

&& Integer.valueOf(number.charAt(1)) <= 5);

}

// more code boolean code

}

My professor said to redo it because it isn't a good design pattern to solve it. She said the responsibility should not be the job of the factory but of the subclasses.

My solution:

class CreditCardFactory {

public static CreditCard createCard(String number){

CreditCard cc[] = { new AmExCC(number), new VisaCC(number)};

for(int index=0; index<cc.length; index++)

if(cc[index].isMyType())

return cc[index];

return null;

}

}

网友答案:

From my point of view you only have to move those boolean methods to the concrete classes. The factory method might then look similar to this:

static CreditCard createCard(final String number) {

    if (MasterCC.isValidNumber(number)) {
        return new MasterCC(number);
    }

    if (VisaCC.isValidNumber(number)) {
        return new VisaCC(number);
    }

    if (AmExCC.isValidNumber(number)) {
        return new AmExCC(number);
    }

    if (DiscoverCC.isValidNumber(number)) {
        return new DiscoverCC(number);
    }

    return null;
}
相关阅读:
Top