Factory mode: defines an interface used to create objects, so that its subclass determines which class to instantiate. This delays the class Instantiation to the subclass.
1. Common factory model:
Public class goodproduct implements product {
Private string prodinfo = "Iam the good Prod ";
Public String getproductinfo (){
// Todo auto-generated method stub
Return this. prodinfo;
}
Public void setprodinfo (string prodinfo ){
// Todo auto-generated method stub
This. prodinfo = prodinfo;
}
}
Public class badproduct implements product {
Public String getproductinfo (){
// Todo auto-generated method stub
Return "Iam the bad product ";
}
Public void setprodinfo (string prodinfo ){
// Todo auto-generated method stub
}
}
Public class prodcreator implements creator {
Public <t extends product> T getprod (class <t> C ){
// Todo auto-generated method stub
T ret = NULL;
Try {
Ret = (t) class. forname (C. getname (). newinstance ();
} Catch (instantiationexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (illegalaccessexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (classnotfoundexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Finally {
Return ret;
}
}
}
2. Factory models for Multiple factories:
Public class badprodcreator {
Public Product getprod (){
Return new badproduct ();
}
}
Similarly, goodprodcreator.
Call method:
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Prodcreator Pc = new prodcreator ();
Goodproduct Gp = pc. getprod (goodproduct. Class );
System. Out. println (GP. getproductinfo ());
Badproduct BP = pc. getprod (badproduct. Class );
System. Out. println (BP. getproductinfo ());
Gp = simplecreator. getprod (goodproduct. Class );
BP = simplecreator. getprod (badproduct. Class );
System. Out. println (GP. getproductinfo ());
System. Out. println (BP. getproductinfo ());
Badprodcreator BPC = new badprodcreator ();
System. Out. println (BPC. getprod (). getproductinfo ());
}
Abstract Factory mode: Provides interfaces for creating a group of related or interdependent objects without specifying specific classes.