title: Design Pattern for returning a credit card base on a boolean
body: <p>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.</p>
  
  <p>Here is my code: </p>
  
  <pre><code>abstract class CreditCard{
  
      String cardNumber;
  
      public CreditCard(String number) {
          cardNumber = number;
      }
  }
  </code></pre>
  
  <p>All of my subclass such as MasterCard, Visa, etc extends the CreditCard superclass.</p>
  
  <p>Example of one of my subclass:</p>
  
  <pre><code>class MasterCC extends CreditCard {
  
      public MasterCC(String number) {
          super(number);
      }
  }
  </code></pre>
  
  <p>I chose a Factory Design Pattern</p>
  
  <pre><code>class CreditCardFactory {
  
      static CreditCard createCard(String number) {
          CreditCard cc = null;
  
          if (number.length() == 0 || number.length() &gt; 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' 
              &amp;&amp; 1 &gt;= Integer.valueOf(number.charAt(1)) 
              &amp;&amp; Integer.valueOf(number.charAt(1)) &lt;= 5);
      }
      // more code boolean code
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>My solution:</p>
  
  <pre><code>class CreditCardFactory {
  
  
       public static CreditCard createCard(String number){
              CreditCard cc[] = { new AmExCC(number), new VisaCC(number)};
  
               for(int index=0; index&lt;cc.length; index++)
                      if(cc[index].isMyType())
                           return cc[index];
  
       return null;
  }
  </code></pre>
  
  <p>}</p>