Design Patterns — Zero to Hero — Abstract Factory Pattern

Abstract Factory relies on object composition. Object creation is implemented in methods exposed in the Factory interface.

Intent of the Abstract Factory Pattern is to create families of related objects without having to depend on their concrete 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