: If object creation code is spread
in whole application, and if you need to change the process of object creation
then you need to go in each and every place to make necessary changes.
ècreates objects without exposing the instantiation logic to the client
èrefers to the newly created object through a common interface
Exapmle:
Step1.-->
Create
interface:
Shape.java
Interface Shap{
public void drowshape();
}
Step2.-->
Implment interface with Class
Create Class
Rectangle.java
Public class Rectangle implements Shape
{
Public void drowshape(){
system.out.println(“Rectangele Drown”);}}
}
Circle.java
Public class Circle implements Shape
{
Public void drowshape(){
system.out.println(“Rectangle Drown”);}
}
Step.3à
Create Producer class
shapeFactory.java
public classs shapeFactory
{
Public Shape getShape(String Shape)
{
Switch(Shape)
{
Case “Rectangle”:
Return new Rectangle();
Case “Circle”:
Return new Circle();
}
Return null;
}
}
Step..4à
Create Main class
MyMain.java
Public class MyMain
{
Public static void main(String[] a)
shapeFactory sp=new shapeFactory ();
Shape shape1=sp.getShape(“Circle”);
Shape1.drawShape();//same for second one so
based on the the given classes name
}
}
Comments
Post a Comment