I am implementing factory design pattern in java

Viewed 2061

I am implementing factory design pattern in java where I want to keep one overloaded method in abstract class. Will it violate the factory pattern concept? Or please suggest whether this is right way to implement Factory design pattern ?

abstract class A{
    void meth(int a);
    void meth(int a,int b);
}

class Factory{
    public static A factoryMethod(int a){
         if(a==1){
            return new Ob1();
        }else{
            return new Ob2();
        }
    }
}

class Ob1 extends A{

void meth(int a){}
void meth(int a,int b){}
}
3 Answers

Here is an example of Java factory implementation.

Let's say we have a requirement to create multiple currencies support and code should be extensible to accommodate new Currency as well. Here we have made Currency as interface and all currency would be a concrete implementation of Currency interface.

Factory Class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and extensible.

Here is complete code example of Factory pattern in Java.

The Currency classes:

interface Currency {
       String getSymbol();
}
// Concrete Rupee Class code
class Rupee implements Currency {
       @Override
       public String getSymbol() {
              return "Rs";
       }
}

// Concrete SGD class Code
class SGDDollar implements Currency {
       @Override
       public String getSymbol() {
              return "SGD";
       }
}

// Concrete US Dollar code
class USDollar implements Currency {
       @Override
       public String getSymbol() {
              return "USD";
       }
}

The Factory:

// Factory Class code
class CurrencyFactory {

       public static Currency createCurrency (String country) {
       if (country. equalsIgnoreCase ("India")){
              return new Rupee();
       }else if(country. equalsIgnoreCase ("Singapore")){
              return new SGDDollar();
       }else if(country. equalsIgnoreCase ("US")){
              return new USDollar();
        }
       throw new IllegalArgumentException("No such currency");
       }
}

// Factory client code
public class Factory {
       public static void main(String args[]) {
              String country = args[0];
              Currency rupee = CurrencyFactory.createCurrency(country);
              System.out.println(rupee.getSymbol());
       }
}

Check out for more Java Factory pattern examples.

Related