group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
263 Members
Join this group to post and comment.
Soubhik Maji
Soubhik Maji
Computer Science
31 Jan 2019

Factory Pattern

Factory Design Pattern 


1.When you want  a method to return one of several child classes of a common super class


2.Create a child class object at run-time , choosing it based on some random logic .


3.And having directly randomize functions or some logic in the main program , in which the user also has the ability to imprint his inputs is bad . This leaves the code open to be modified , also having bunch of if-else statements in the main program is bad as well .


4.Instead we use Factory pattern , okay let's take an example ..suppose we have ang weapon interface and two implementation -

1. rocketlauncher 

2.Automatic Gun 


5.Now we create one of the above bases on user input ...but this is bad ...(read 3rd point ) mixing user inputs and such objects creation ..will be vulnerable to modifications. So we create a 


6.Class WeaponFactory ...it will have a function that will take user input and based on that create and return either rocketlauncher  or Automatic Gun  or return null ...


This is going to completely encapsulate weapon creation...so whenever we have to modify something there's only one place where we have to modify .


So that was a Simple Factory ..