Sunday 25 September 2022

 Design Patterns (Java): Factory Design Pattern

a)Factory Design Pattern:

In this design pattern, we have an interface with methods defined in it and then that interface is called and methods are implemented with logic internally.


E.g.:


public interface Bottle {

void cap();

int shape();

String color();

}

This interface: bottle, is now implemented by concrete classes below:

a) public class OilBottle implements Bottle {

  String capShape = "Circular";

 String capMaterial = "aluminium";

  @Override

   public void cap() {

   System.out.println("The cap is : " + capShape +  "and " + capMaterial + "with company logo on it");

}

 String bottleShape = "Cylindrical";

 int height = 12;

 int diameter = 10;

int volumeBottle;

  

  public int shape(){

   System.out.println("The bottleShape is : " + bottleShape);

  areaBottle = 3.14 * height * (diameter/2)*(diameter/2);

  return areaBottle;

}


 String bottleColor = "red";  

public String color(){

  return bottleColor;

}

}

Now, if we want to create different product bottles like juice bottle, sauce, ketchup, solutions, spray, chemical formula, baby product and so on, we have to call interface Bottle and implement its methods with logic in it.

No comments:

Post a Comment