Subscribe to Java/SCJP        RSS Feed
-----

Factory Method Pattern

Icon Leave Comment
Obect instatiation is a critical part of any application. If a class is creating an instance of other then it has to know the way to get the instance. The instatiation can be decoupled using the factory class. The factory class is responsible for returning an instance to the requester class. Usually it is the constructor that returns the instance but it can be anyother method that does the job in case of factory class.

Due to decoupling, the factory class can be used to select the instance required by the requester class. The factory class depending upon the argument passed to it decides which class' instance is to be returned.


e.g.
class AddressFactory {
 Object getInstance(arg) {
	if(arg==1){
	  return (new usaddress);
	} else {
	  return (new indiaaddress);
	}
  }
}

class usaddress implements address{
}

class indiaaddress implements address{
}

interface address {
}

class requester {
AddressFactory addrfactory = new AddressFactory();
address addr = addrfactory.getInstance(1); //getting usaddress

}

0 Comments On This Entry

 

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Recent Entries

Recent Comments

Search My Blog

11 user(s) viewing

11 Guests
0 member(s)
0 anonymous member(s)