I am implementing a factory design pattern in java

I am implementing a factory design pattern in java where I want to store one overloaded method in an abstract class. Would this violate the concept of a factory pattern? Or ask if this is the right way to implement the 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){}
}

      

+4


source to share


3 answers


To implement first Factory Pattern

, you must consider what will produce Factory

. Let them do it Vehicles

.

public VehicleFactory {
   public Vehicle newVehicle(String type) {
      ...
   }
}

      

which will output Vehicles

according to the class hierarchy below.

public interface Vehicle {
   public List<Door> getDoors();
}

public class Motorcycle implements Vehicle {
   public List<Door> getDoors() {
       return Collections.<Door>emptyList();
   }
}

public class SportsCar implements Vehicle {
   public List<Door> getDoors() {
       return Collections.<Door>unmodifiableList(Arrays.asList(new Door("driver"), new Door("passenger"));
   }
}

public class Hatchback implements Vehicle {
       public List<Door> getDoors() {
       return Collections.<Door>unmodifiableList(Arrays.asList(new Door("driver"), new Door("passenger"), new Door("back"));
   }
}

      

Then your method VehicleFactory

newVehicle(...)

might look like

public Vehicle newVehicle(String type) {
    if ("motorcycle".equals(type)) { return new Motorcycle(); }
    if ("sports car".equals(type)) { return new SportsCar(); }
    if ("hatchback".equals(type)) { return new Hatchback(); }
    return null;
}

      

Now the main question is: "Why do you need this?"

Sometimes you need a good clean interface to create lots of related content. You give the related elements an interface and a factory to build them. This allows someone using this piece of software to just include the Interface class and ItemFactory. They don't see the individual details, which simplifies their code.

Since you have hidden the implementation details of everything Vehicles

in the code above, if you had a programming error (or wanted to add something), you can fix one of Vehicles

(or add a new one Vehicle

) at the factory and re-release the library (JAR file). containing VehicleFactory

.

You know other people have used methods VehicleFactory

, so you don't have to worry about their code breaking at compile time, and if you didn't care, you can also make sure it will work at runtime.

This is not the same as saying that behavior will not change. New implementations Vehicle

will be rolled back, hopefully with fewer inline bugs. Also, since they didn't ask about the "new vehicles" you might have added, they won't see them until they call newVehicle("station wagon")

or something.

Also, you can change the way you build Vehicles

. For example, if you later decide that you do not need a simple "just construct it in one pass" implementation style, you can change 'newVehicle (...)' as follows

 public Vehicle newVehicle(String type) {
    Chassis chassis;
    if ("motorcycle".equals(type)) {
       chassis = new TwoWheelChassis();
    } else {
       chassis = new FourWheelChassis();
    }
    return new ComponentVehicle(chassis, getDoorCount(type));
 }

      



where ComponentVehicle

implements Vehicle

and for some reason requires an explicit object Chassis

.

--- update after seeing the question "number of methods" in the comments ---

Factory pattern

actually not about the number of methods, but about one method capable of constructing an abstract thing from one or more concrete things.

So in the above example, I could have

public VehicleFactory {
    public Vehicle newVehicle(String type) { ... }
    public Vehicle newRedVehicle(String type) { ... }
    public Vehicle newBlackVehicle(String type) { ... } 
}

      

And they would all be acceptable factory methods in terms of type Vehicle

, but they would not be factory oriented methods in terms of color Vehicle

.

To get a factory method that can handle Type and Color at the same time, the factory method

    public Vehicle newVehicle(String type, String color) { ... } 

      

can be added. Note that sometimes some combinations don't make any sense, so it might not be worthwhile to combine all the factory methods into one factory method.

Any method in your factory object is not really a factory method unless it has the ability to return more than one base interface type. Likewise, it is not a factory method if you need to specify how to construct an object outside of the method.

If you need to transfer control over how to create a Vehicle

"this would be a factory" method to your client, while providing some security when used in a sensible manner, you do Builder pattern

. An example of how different Builder Pattern

can be seen in the client code below

 VehicleBuilder builder = new VehicleBuilder();
 builder.addDoor("driver");
 builder.addDoor("passenger");
 builder.paintVehicle("red");
 Vehicle vehicle = builder.getVehicle();

      

+4


source


Factory pattern is a vague term, no? There are simple factories, Factory methods, and abstract factories. I think you are talking about Simple Factory here. https://www.codeproject.com/Articles/1131770/Factory-Patterns-Simple-Factory-Pattern



+1


source


Here is an example implementation of a Java factory.

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

The factory class creates a currency based on the country and returns a concrete implementation that will be stored in the interface type. This makes the code dynamic and extensible.

Here is a complete example of template code Factory

in Java.

Classes Currency

:

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";
       }
}

      

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 other Java Factory examples .

0


source







All Articles