Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Factory Method Design Pattern

This is one of the Creational Design Pattern,The use of this pattern is to make the classes loosely coupled.
ComputerFactoryIF-id
Client Code which calls creation of computer and who only knows which object to create ,In this case It asks to create an Apple Computer and Give it using ComputerFactoryIF.
Computer aComputer = ComputerFactoryIF.createComputer("apple");
System.out.println(aComputer.getName()); 


The ComputerFactoryIF the interface of all the concrete factories checks as to which type of Computer is to be created and delegates to the appropriate ComputerFactory in this case AppleComputerFac


public class ComputerFactoryIF {

public static Computer createComputer(String string) {
Computer aComp = null;
if (string.equals("apple"))
aComp = AppleComputerFac.createComputer();
else if (string.equals("dell"))
aComp = DellComputerFac.createComputer();
return aComp;
}



There After the corresponding factory creates an instance of the computer and returns(In this case AppleComputer Object).


public class AppleComputerFac extends ComputerFactoryIF {
public static Computer createComputer() {
return new AppleComputer();
}
}



public class AppleComputer extends Computer {
AppleComputer() {
this.name = "AppleComputer";
}
}


 

2 comments:

  1. Check the method createComputer in ComputerFactoryIF, the return value refers to non existent variable a aPerson.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

Search 24 Bytes