Saturday, 15 February 2020

Factory Pattern

Factory Pattern:
1)     Main intension loosely coupling.
2)     Creates objects without exposing the instantiation logic to the client.

3)      refers to the newly created object through a common interface


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

Class Triangle implements Shape {
         Public void size() {
               System.out.println (“Triangle”);
         }
}

Class Client {
    Public static void main(String[] args) {
          Shape s = new Rectangle();
    }
}


Now the relationship between Client and Shape Tightly Coupled.


Now I need to break tight coupling between client and shape



Class Factory {

    Public static Shape getShape(int arg) {
             Shape s;
             If(arg=0) {
                  s = new Rectangle();
              } else {
                  s = new Triangle();
              }
          return s; 

     }

Ramesh Comments: Now creation Shape object taken care by Factory using Factory Method getShape,

Relationship between Factory and Shape Tightly Coupling.

Class Client {
      public static void main(String[] args) {
             Shape s = Factory.getShape(0);
              System.out.println(s.szie());
      }
}


Relationship between Client and Shape loosily coupled due to Factory Method creating objects.

Factory Main intension brings loosily coupling with client.

Now Client not creating the shape object, Factory method creating the shape object, Client doesn't know internal implementation of Factory Method. This is called "Encapsulation".




No comments:

Post a Comment