If you have a class which has specific methods, variables, properties which always need to be set and run and possibly not on the construction of the class, using the Builder Pattern is a very useful way to do this.
The Builder Pattern is a clearer and more efficient way of setting up the environment of a class.
If you were to set and run methods, variables, properties on construction of the class you might as well do this in the class's constructor method.
But if you wanted to set specific environment setting a bit later then builder methods are ideal
Here is the code of a class that uses the Builder Pattern
public class ThisClass{
private String HerName;
private String HerJob;
private String Herotherjob;
public ThisClass setName(String passName){
HerName=passName;
return this;
}
public ThisClass setJob(String passJob,String otherjob){
HerJob=passJob;
Herotherjob= otherjob;
return this;
}
public ThisClass setJob(String passJob){
HerJob=passJob;
return this;
}
}
This invokes the Builder Pattern class above and uses the Builder Pattern on lines 2 and 3. As you can see all the work was done on just 1 line.
1. ThisClass cls = new ThisClass();
2. cls.setName('Liz').setJob('Secret Agent','Window Cleaner'); //This uses the 1st variety of setJob
3. cls.setName('Liz').setJob('Secret Agent'); //This uses the 2nd variety of setJob
For more information and a useful example on the Builder Pattern see http://developer.force.com/cookbook/recipe/email-utility-class
No comments:
Post a Comment
Note: only a member of this blog may post a comment.