Design Patterns — Zero to Hero — Abstract Factory Pattern

Let's take an example of a scenario to implement this pattern in real-word.

I want to implement a system for the Cloth showroom where Men and Women wares sold. To get particular people wares we have come up with Abstract Factory Pattern where it uses interface/abstract classes to hide the concrete classes and wrap up all those into an Abstract Factory class.

public interface MaterialType {
void getName();
}
public class LongSleeveTop implements MaterialType {
@Override
public void getName() {
System.out.println("Long Sleeve Top for Woman");
}
}
public class Scarf implements MaterialType {
@Override
public void getName() {
System.out.println("Scarf for Woman");
}
}
public class MenShirt implements MaterialType {
@Override
public void getName() {
System.out.println("Shirt for Men");
}
}
public abstract class AbstractFactory {
abstract Shape getMaterialType(String mateType) ;
}
public class MenWearFactory extends AbstractFactory {@Override
public Shape getMaterialType(String mateType){
if(mateType.equalsIgnoreCase("MenShirt")){
return new MenShirt();
}else if(mateType.equalsIgnoreCase("MenTrouser")){
return new MenTrouser();
}
return null;
}
}
public class WomenWearFactory extends AbstractFactory {@Override
public Shape getMaterialType(String mateType){
if(mateType.equalsIgnoreCase("Scarf")){
return new Scarf();
}else if(mateType.equalsIgnoreCase("LongSleeveTop")){
return new LongSleeveTop();
}
return null;
}
}
public class FactoryProducer {   public static AbstractFactory getFactory(boolean men){   
if(men){
return new MenWearFactory();
}else{
return new WomenWearFactory();
}
}
}
public class Client {   public static void main(String[] args) {      //get MenWear factory
AbstractFactory menFactory = FactoryProducer.getFactory(false);
//get an object of MaterialType Men Shirt
MaterialType cl1 = menFactory.getMaterialType("MenShirt");
//call getName method of MaterialType MenShirt
cl1.getName();
//get an object of MaterialType Trousers
MaterialType cl2 = menFactory.getMaterialType("Trousers");
//call getName method of MaterialType Trousers
cl2.getName();
//get WomenWearFactory
AbstractFactory womenFactory = FactoryProducer.getFactory(true);
//get an object of Shape Rectangle
MaterialType cl3= womenFactory.getMaterialType("Scarf");
//call getName method of MaterialType Scarf
cl3.getName();
}}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store