Skip to main content

Abstract Factory pattern in java

       In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.
 Abstract Factory  is Factory within factory. Its  come under creational Design Pattern in java


Example:

Stepà1.create interface
Shape.java
 Public interface Shape
{
Public void drawshape();
} 
Color.java
Public interface Color
{
Public void setcolor();
 }

Stepà2.implments shape

Rectangle.java

Public  Class  Rectangle implements  Shape
{
void drawshape()
{
System.out.println(“Rectangle drwn”);
}

}


Circle.jva

Public  Class  Circle implements  Shape
{
void drawshape()
{
System.out.println(“Circle  drwn”);
}

}
Step.3àimplements color Interface

Red.java
Public class Red implements Color
{

  Public void setcolor()
{
System.out,println(“Red Color Filled”);
}

}


Green.java
Public class Green  implements Color
{

  Public void setcolor()
{
System.out,println(“Red Color Filled”);
}

}


Step.4àcreate  Abstract Class

Public class abstract  Myabstract
{
abstract Shape getshape(string shape);
abstract Color getcolor(string color);
}




Step.5àinherit abstract class
 ShapeFactory,java
Public class ShapeFactory extends Myabstract

{
Shape getshape(string shape)
{
If(shape.equals(“Rectangle”))
  Return new Rectangle();
elseif(shape.equals(“Circle”))

Return new Circle();

}
Color getcolor(string color)
{
Return null;
}


}

ColorFactory.java
Public class ColorFactory extends Myabstract

{
Shape getshape(string shape)
{

Return null;

}

Color getcolor(string color)
{
If(shape.equals(“Red”))
  Return new Red();
elseif(shape.equals(“Green”))

Return new Green ();

}


}


Step.6àcreate  factory Producer class for making object of Shape and Color Factory.

MyProducer.java
Public class MyProducer
{
Public static  Myabstract getfactory(string FactType)
{
If(shape.equals(“Shape”))
  Return new Shape();
elseif(shape.equals(“Color”))
    return new Color();

}
}

Step.6àcreate main class to acesss all the hiarchy
Mydemo.java
Public class mydemo
{
Public static void main(string [] s)
{

Myabtsract  shpefactory=MyProducer. getfactory(“Shape”);
Shape sp1= shpefactory.getshape(“Rectangle”);
Sp1.drawShap();
//for color factory
Myabtsract  colorfactory=MyProducer. getfactory(“Color”);
Color clr= colorfactory.getcolor(“Red”);
Clr.sercolor();


}
}







Comments