What is Builder Pattern

Hi
I am new to design patterns andI want to know about Builder pattern.
I gone through some document from google. and came to know that it is used to separate the complex type of objects relationship from its representaion. I also gone through the code. Like some Director,Builder,ConcreteBuilder class defined in the sample code. So are these classes are mandatory to use this pattern or we can define our own ?
Can anybody explain it with example.?
Thank/Regards
Chintan

The <a href"http://www.softwareleadership.org/pages/J2EEGlossary.xml#B">Builder</a> design pattern is a fancy one. It is used to separate the "Construction" process of a complex object that is (typically created in steps) from its representation, whatever that may be.
It is closely similar to the Abstract Factory pattern. However the focal point of Abstract Factory is on groups of objects (either similiar or complex). The Abstract Factory returns an object immediately, the Builder typically returns an object after two or more steps. Here is a example.
You need to create a Policy object. The Policy object will contain rules for sale discounts, tax rules, fees, and warantees.
To create a Policy object, it must interact with a (1)Tax Manager, (2)Sale Manager and (3)Fee Manager.
The representation of the final Policy object (which can have different rules and behavior each time one is created) must be separated from the process of how it is created. This is necessary so that we can use the same "construction process" to create an infinte number of "policy object" representations. We need low coupling between the algorithm used to create the complex object and the object itself (the representation).
In this example, the role of Director is implemented in a class called PolicyManager. PolicyManager has one method called
"constructPolicy(String s)"
In this example, the role of Builder is implemented in an interface class called PolicyBuilder. This class has a method called "buildPolicy()". This method returns an object called Policy. To create a Policy object, it must be passed to a TaxManager, SalesManager and a FeeManager. A Chain of Responsibility can be implemented to contain the algorithm of the "creation process".
This design pattern enables us to separate the representation (whatever that may be) of a "final" object from the steps it goes through for creation.
Best,
Sam
http://www.softwareleadership.org

Similar Messages

  • Implementing a Builder Pattern (Not Necessarily Gof)

    What I am looking for is some examples (ref. Joshua Bloch's Builder) on a plain java object such that:
    // has a min. set of required properties and I can
    // add any number of optional properties and then
    // call a single build method to return me an instance
    // of type Message
    class Message {
    private int id;
    private String title;
    private String author;
    // optional
    private String summary;
    private double txCost;
    public Message(int id, String titile, String author) {
    // normal this.id = id , etc...
    public Message summary(String summary) {
    public Message txCost(double txCost) {
    public Message build() {
    // this actually returns the new instance with min and opt params
    // Message m = Message(1, "Title","dk").summary("summa").build();
    Thanks

    I agree with dubwai that you wouldn't implement a build method in the class you have already created, that returns another instance of itself
    I also don't think you should preface your request with "not necessarily GoF". I think J.B. was definitely suggesting a good application of the GoF builder pattern in order to make immutable objects elegant and relatively easier to deal with.
    In the end, you are trying to satisfy at least 2 things. (I'm sure there are others)
    1. Turn a mutable POJO into an immutable object.
    2. Provide an elegant creation mechanism for initializing the object without having long winded, and type ambiguous construction.
    Your example doesn't necessarily require the addition of a builder to make your Message immutable, but let me provide you the example anyway.
    // has a min. set of required properties and I can
    // add any number of optional properties and then
    // call a single build method to return me an instance
    // of type Message
    public class Message {
        // make these properties "final". This makes them immutable
        private final int id;
        private final String title;
        private final String author;
    // optional
       private final String summary;
       private final Double txCost; /*convert to immutable wrapper, allows simulation of
                                                           "optional", i.e. null means wasn't used in initialization */
    /* cannot construct a message without the use of a builder */
    private Message(Builder builder) {
         this.id = builder.id;
         this.title = builder.title;
         this.author = builder.author;
         this.summary = builder.summary;
         this.txCost = builder.txCost;
    // normal this.id = id , etc...
    // getters for properties
    // end getters
       /* Note, the Builder is a static inner class, it is only relevant for creating instances of
          Message.
       public static class Builder{
        // short lived mutables
             private int id;
             private String title;
             private String author;
            private String summary;
            private Double txCost;
            /* you cannot have a Message without these required fields, so we force them
              in the constructor */
            public Builder(int id, String title, String author){
                this.id = id;
                this.title = title;
                this.author = author;
            /* I prefer the setter names, but the Builder behavior of returning the this object */
            public Builder setSummary(String summary){
                this.summary = summary;
                return this;
            public Builder setTxCost(double txCost){
                 this.txCost = txCost; // note Java 1.5 autoboxing/unboxing
                 return this;
            public Message build() {
                 return new Message(this);
    } Now you can create four different permutations of Message
    Message basic = new Message.Builder(1,"A MIDSUMMER NIGHT'S DREAM", "WILLIAM SHAKESPEAR").build();
    Message summary = new Message.Builder(2, "SOLARIS","STANISLAW LEM").setSummary("Great Sci-Fi book, bad movie").build();
    Message txCosted = new Message.Builder(3, "FIGHT CLUB","CHUCK PALINIUK").setTxCost(30,000,000.00).build();
    Message all = new Message.Builder(4, "BUILDER","DANIEL SHAW").setSummary("Check out the builder eclipse plug-in at sourceforge").setTxCost(0.0).build(); //Shameless self promotion

  • Builder pattern

    Hello,
    I am new to design patterns, but willing to learn. So I came here for an advice, as this would be my first attempt in implementing the builder pattern.
    The project: Create a java application that will generate and send via email 6 exports (Excel files) of different types, having their data filled from a database. The names of the exports, as well as other filters, will be read from an XML.
    My solution was to use the builder pattern, as it follows:
    Buider:
    public abstract class BuilderExport {
         protected Expor export;
         public Export getExport(){
              return export;
         public void createExport(){
              export = new Export();
         public abstract void createAntet();
         public abstract void createTableHead();
         public abstract void createTable();
         public abstract void setPath();
    ConcreteBuilder:
    public class BuilderExportImplementationA extends BuilderExport {
           @Override
         public void createAntet() {
              // TODO Auto-generated method stub
                    *export.setSheet() and export.setWorkbook()*
           @Override
         public void createTableHead() {
              // TODO Auto-generated method stub
                    *export.setSheet() and export.setWorkbook()*
           @Override
         public void createTable() {
              // TODO Auto-generated method stub
                    *export.setSheet() and export.setWorkbook()*
           @Override
         public void setPath() {
              // TODO Auto-generated method stub
                    *export.setPath()*
    Director:
    public class DirectorExport {
         private BuilderExport builder;
         public DirectorExport (BuilderExport b){
              this.builder= b;
         public Export getExport(){
              return builder.getExport();
         public void createExport(){
              builder.createExport();
              builder.createAntet();
              builder.createTableHead();
              builder.createTable();
                    builder.setPath();
    Product:
    public class Export {
         private Workbook workbook;
         private Sheet sheet;
            private String path;
            public Export(){
                     workbook = new HSSFWorkbook();
         public void setPath(String path) {
              this.path = path;
         public String getPath() {
              return path;
         public Workbook getWorkbook() {
              return workbook;
         public void setWorkbook(Workbook workbook) {
              this.workbook = workbook;
         public Sheet getSheet() {
              if (sheet == null)
                   sheet = workbook.createSheet();
              return sheet;
         public void setSheet(Sheet sheet) {
              this.sheet = sheet;
    Application:
            public static void main(String[] args) {
              BuilderExport builder = null;
              List<ExportFilters> listFilters;
              DirectorExport director;
              for (ExportFilters fe : listFilters) {
                   if (fe.getType().equals("A")) {
                        builder = new BuilderExportImplementationA ();
                   } else if (fe.getType().equals("B")) {
                   director= new DirectorExport (builder );
                   director.createExport();
         }Can someone please tell me if this design is well thought? I would appreciate any help you can give me.
    An other question: Keeping in mind that the XML with the requested filters is received as a param in the command line, how can I have access to the filters in the ConcreteBuilder classes? it is a good design to pass it as an argument to the constructor, like
    new BuilderExportImplementationA (ExportFilters fe)
    Also, the methods saveExport(String path) and sendExport(..) to which object will they belong?
    Thanks.
    ps: Please excuse my grammar, as english is not my native language.
    Edited by: user13806367 on Jan 21, 2011 2:19 AM

    Thank you both for your answers.
    Let me see if I understood well how this pattern works. So, if for example my Export class would be
    public class Export {
         private Antet antet;
         private TableBody body;
         private String location;
    }and I would use the builders only to construct Antet, TableBody and location, but the actual construction of the excel file would be done in the Export class, then the use of the builder pattern would be justified? This is just a scenario.
    As for the 'filters', i'm sorry for not explaining what they're all about, but as Jschell well presumed they are used to query the data from database. The problem here is that for each export I would have to construct a query from different tables, using different ordering. There are 5 or 6 tables that are always present in the query, but there are other 4 or 5 tables that may vary. The filters are read from an xml file, which will look something like that:
    <generation-export>
         <export type="km">
              <filtres>
                   <year>2011</year>
                   <month>09</month>
                   <statut>tous</statut>
                   <typ_p>PP</typ_p>
                   <division>NORD</division>
                   <pdr>YYY</pdr>
              </filtres>
         </export>
    </generation-export>Could you tell me what is the best way to construct those querys?
    Thanks again.
    Best regards.

  • Trying to implement the Builder pattern with inheritance

    This is just a bit long, but don't worry, it's very understandable.
    I'm applying the Builder pattern found in Effective Java (J. Bloch). The pattern is avaiable right here :
    http://books.google.fr/books?id=ka2VUBqHiWkC&lpg=PA15&ots=yXGmIjr3M2&dq=nutritionfacts%20builder%20java&pg=PA14
    My issue is due to the fact that I have to implement that pattern on an abstract class and its extensions. I have declared a Builder inside the base class, and the extensions specify their own extension of the base's Builder.
    The abstract base class is roughly this :
    public abstract class Effect extends Trigger implements Cloneable {
        protected Ability parent_ability;
        protected Targetable target;
        protected EffectBinder binder;
        protected Effect(){
        protected Effect(EffectBuilder parBuilder){
            parent_ability = parBuilder.parent_ability;
            target = parBuilder.target;
            binder = parBuilder.binder;
        public static class EffectBuilder {
            protected Ability parent_ability;
            protected Targetable target;
            protected EffectBinder binder;
            protected EffectBuilder() {}
            public EffectBuilder(Ability parParentAbility) {
                parent_ability = parParentAbility;
            public EffectBuilder target(Targetable parTarget)
            { target = parTarget; return this; }
            public EffectBuilder binder(EffectBinder parBinder)
            { binder = parBinder ; return this; }
        // etc.
    }And the following is one of its implementation :
    public class GainGoldEffect extends Effect {
        private int gold_gain;
        public GainGoldEffect(GainGoldEffectBuilder parBuilder) {
            super(parBuilder);
            gold_gain = parBuilder.gold_gain;
        public class GainGoldEffectBuilder extends EffectBuilder {
            private int gold_gain;
            public GainGoldEffectBuilder(int parGoldGain, Ability parParentAbility) {
                this.gold_gain = parGoldGain;
                super.parent_ability = parParentAbility;
            public GainGoldEffectBuilder goldGain(int parGoldGain)
            { gold_gain = parGoldGain; return this; }
            public GainGoldEffect build() {
                return new GainGoldEffect(this);
        // etc.
    }Effect requires 1 parameter to be correctly instantiated (parent_ability), and 2 others that are optional (target and binder). Implementing the Builder Pattern means that I won't have to rewrite specific construcors that cover all the combination of parameters of the Effect base class, plus their own parameter as an extension. I expect the gain to be quite huge, as there will be at least a hundred of Effects in this API.
    But... in the case of these 2 classes, when I'm trying to create the a GoldGainEffect like this :
    new GainGoldEffect.GainGoldEffectBuilder(1 , locAbility).goldGain(5);the compiler says "GainGoldEffect is not an enclosing class". Is there something wrong with the way I'm trying to extend the base Builder ?
    I need your help to understand this and find a solution.
    Thank you for reading.

    The GainGoldEffectBuilder class must be static.
    Otherwise a Builder would require a GainGoldEffect object to exist, which is backwards.

  • What are design patterns ?

    what are design patterns ?
    what is the difference between design patterns and frameword ?
    any help would be really appreciated !!

    A quick [url http://www.google.com/search?hl=en&q=what+are+design+patterns+%3F+&btnG=Google+Search&meta=] google  will bring more answers than you know what to do with.

  • What does "Build" mean in OS X Mavericks 10.9.2?

    Like
    Mac OS X Mavericks 10.9.2 Build 13C53?
    Mac OS X Mavericks 10.9.2 Build 13C39?
    Mac OS X Mavericks 10.9.2 Beta Build 13C48?
    Does it mean previous releases?
    Like what they have in Wikipedia
    Snapshot

    What SilverSkyRat said.
    In addtion, the software developers, internal test groups, outside beta testers need to be able to report problems and specify a specific nightly build, so that the developer can go back to that version and verify what changes went into that build that might have caused the problem.
    It also allows internal testers and beta testers a way to know that the version they are running is older (newer) then another version that is being offered for testing.
    It also allows developers to tell all testers that they should NOT install a specific build, if it is discovered that it is a bad build.
    Essentally, the development process needs a way to communicate what nightly build is what, and be able to associate bugs during development with a specific build.
    And generally that build number can be used to get the exact sources from a source code control system that was used to create that build.
    The same as SilverSkyRat, I do not know the exact process inside Mac OS X development, but what SilverSkyRat and I have described is what I've experienced at several different software development companies which develop Unix operating systems and Unix software for sale.
    And finally, the build numbers you see in your released Mac OS X version, is just the build number where they decided to declare Golden Master for shipping to customers.
    Message was edited by: BobHarris

  • Difference between Builder Pattern and Factory Pattern

    difference between Builder Pattern and Factory Pattern

    You are right Both of these patterns are creational design patterns Purpose of these two patterns is very different as Abstract Factory Patterns (which is commonly known as Factory pattern ) is used to create a object in a scenario when you have a product & there is a possibility of many vandors providing implementation for it. So it is good to come up with a abastract factory which provides create method for the product. Each vendor can implement you abstract factory & provide a concrete implementation which will return a product of Vendor implementation.
    Builder patter is used in case you have a very complex object creation process involved & you realy want to abstract the client from doing all those complex steps. In such situation you create a builder class which takes care of all complex steps & client just needs to use this builder class to create your complex object.
    Hope it clarifies your doubts.

  • Builder Pattern - have you used it?

    Hi,
    I am interested in learning patterns for designing my code for my UI's...anyway I have read a little about the Builder Pattern..but was wondering if anyone has used it before, and if so, can they post some sample code of how to code in that pattern, or send me to some links...
    thanks.

    Here's an example...
    http://www.fluffycat.com/java/JavaNotes-GoFBuilder.html

  • What does xsd:pattern[value="\d+"]  mean in an XSD

    Hello friends ,
    i have been given this XSD in which for a field , data type is srting with restriction as xsd:pattern[value="\d+"] , can any one tell me what does this pattern mean . thanks

    Hi,
    "Enumeration root is not present“ means these path do not exist.
    Have you tried to run them with the /v 13 switch to create the most detailed log file.
    For more infomation, please review the links below:
    ScanState Syntax
    http://technet.microsoft.com/en-us/library/hh825093.aspx
    How to Troubleshoot Issues with the User State Migration Tool and the Files and Settings Transfer Wizard
    http://support.microsoft.com/kb/312965
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Does the Builder pattern really need a Director?

    A Builder knows how to construct the various parts of an aggregate, while a Director knows the order in which they should be constructed. Wikipedia illustrates this pattern with a PizzaBuilder example:
    http://en.wikipedia.org/wiki/Builder_pattern
    I find it difficult to understand why one would not move the constructPizza() method (including its implementation) of Waiter (the Director) to PizzaBuilder (the abstract Builder), bypassing Waiter altogether:
    PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
    hawaiianPizzaBuilder.constructPizza();
    Pizza pizza = hawaiianPizzaBuilder.getPizza();Why is it so important to separate the how from the order? To me it looks like having a separate Director class makes things just more complicated without having real benefits.

    Thank you for your reply. Are you suggesting that
    real-world applications have several Directors that
    differ in the order of construction? I just got
    myself the GoF book and it speaks about just one
    Director, which repeats the same construction
    process, independent of the concrete builder passed
    to it.If you look at the Consequences, list item 2 it states:
    "..then different Directors can reuse it to build Product variants from the same set of parts. In the earlier RTF example, we could define a reader for a format other than RTF, say, an SGMLReader, and use the same TextConverters..."
    Note that in the example the Reader is the Director and the TextConverter is the Builder.
    The point of this pattern is to separate the code that knows what to do and the code that knows how to do it so that they can be combined indpendently.
    Suppose you were writing a tool that could take XML or database rows and create a Swing GUI. Let's say you are also asked to take that XML and those database rows and create a web page.
    If you combine the code that reads the input with the code that reads the output, you end up writing the xml reader twice, the database reader twice, the swing builder twice, and the web page builder twice. Then consider what happens if you need a third input format or more output formats.
    I was thinking of using this pattern to create a
    custom JTree in subsequent steps: 1) create the nodes
    from a database, 2) create the tree model, 3) create
    the tree. Right now everything happens in my JTree
    constructor, which doesn't feel right since it's just
    a GUI component. Would that be appropriate? I only
    have one concrete builder now, so it seems a bit too
    much.I would remove any knowledge of the database from your gui component. This doesn't require more code and it won't make things more complicated. I think you'll find that once you have done it, it will make things a lot easier to understand and work on. The idea that every Object should have a single responsibility is poorly defined but is, in my opinion, a very good way to think about your designs.

  • What is Building a List of Used Media?

    Hey there,
    I am capturing around 50 hours of footage off 70 tapes. There's been quite a few breaks in TC and other problems, so I have to re-start the capturing on a regular basia. Now that a lot of the footage is already in the computer, the computer takes a long time to "Build a List of Used Media" before it lets me start capturing. Jus out of curiousity, what is this list, and why does the computer have to build it all the time? Thanks!

    It would seem this web site will answer your question.
    https://m-support.verizonwireless.com/support/terms/products/content_filtering.html
    It makes note of Blackberry devices not compatable see note:
    The service does not work on most Push To Talk devices, any device with a static Internet Protocol address or on search results provided through the Get It Now Search application. The Internet filtering capabilities of the service do not work on phones using WiFi, Mobile Web 1.0, BlackBerry devices or on devices that use Venturi Compression Software, including phones tethered to PCs or PC cards, unless the compression software is turned off. Internet filtering will not work on most advanced devices until you have turned the device off and back on after every Content Filter setting change. The music filtering capabilities of the service do not work on phones with Verizon Music v1.0 software. Call 800-922-0204 or 611 from your handset if you are on a corporate calling plan to determine eligibility to use the service and to activate the service.
    Good Luck

  • Programatically extract x,y posisition found by Vision Builder pattern match

    I would like to write the cordinates found by doing pattern match to a file.  Can this be done with the Vision Builder?

    In the following we proceed to function block search pattern extracted in the previous process (the parameters as rotation angle and minimum score is inserted into SETTINGS control), extract the output of the search function to get the position values indicators that will be displayed on the front panel)
    Atom
    Certified LabVIEW Associate Developer

  • What is ' build indices' and ' drop indices' in a process chain

    Hello ,
    can any one explain me ,In transaction loading process , in a process chain , after activating Data in DS object, what is ' Drop  indices'  and what is 'buid indices'
    Thank you .

    Hi,
       These mostly deal with the indices in a cube. When you load data to a cube, if the indices are present, along with loading the fact tables and dimension tables, the index tables also need to be filled. This requires the system to search for the right location in the index to place a new transaction data row and hence slows down the load.
    Inorder to speed up the loading, the indexes are first deleted, data is then loaded into the cubes,  and the indices are rebuilt. This is a much faster process than loading the cubes with the indexes intact.
    Hope this helps,
    Regards.

  • Builder vs Factory Patterns

    Hi,
    I read about builder and factory patterns. But both of them look quite similar.
    Can u plz help me to understand the difference between them.
    Thanking You,
    Chamal.

    I puzzled over this too. The UML is almost identical for both patterns. A great example of how UML class diagram leave a lot to be desired.
    This is my take, which may not be absolutely correct or orthodox.
    The difference is that in the abstract factory, the point is to hide the implementation of the abstract type. In the builder it's other way around. The point is to hide the implementation of the callers of the builder or really, what is being built.
    So a user of a abstract factory should not know (or care) about what type the abstract factory returns. In the builder pattern, the code could potentially make references to specific builder types (a text builder for debugging or console mode, for example) but the implementation of what is being built is not known to the builder.
    You can easily combine the two and get a lot of flexibility.

  • Builder Design Pattern

    Hi,
    I'm trying to implement the Abstract Builder design pattern for a fairly complex object. If I understand correctly, the builder creates the whole object in one shot; as in, the pieces are hidden from the client while the object is being built. So suppose the object that I need to include as an "ingredient" is more complex. I have a class called Route (with different types that extend it) that requires a list of segments and an origin and destination. The part I'm confused on is how to build a route if I can't provide parameters for it. All the examples I've found so far have had simple objects for the ingredients that didn't require any personalization. Sorry if I'm being unclear. Ask if you need clarification.

    Could be. I'm far from a pattern guru. The key here is to find an approach that works. If perusing a catalog of patterns give you and idea of how to solve your problem, great, use it. On the other hand, if you already have a solution, and it happens to fit a pattern, then cool, now you have a name for what you did. The wrong thing to do would be to try to force it into a particular pattern that doesn't fit.
    The value in patterns is twofold: 1) as a means of communication of some fairly complex, commonly used, abstract concepts, as in, "I suggest a Builder Pattern for this," and the other guy knows exactly what you're talking about, or at least has a general idea and knows where to go for details, and 2) as a catalog of common solutions to existing problems, as in, "Dang it, I have this problem with such-and-such interactions among the pieces, I'm not sure how to structure a solution, but I bet somebody else has done it before... Oh, yeah! Builder Pattern! That'll work!"

Maybe you are looking for

  • How do I use Spotlight to find the location of a document?

    Spotlight used to show the location of document when I hovered the mouse over an item in its list. It no longer does this. Now it tells me that a document exists and allows me to open the document, but doesn't tell me where to find the document. How

  • Variable Screen

    Hi, Can we show a 'Information Message' on the variable screen for 1 particular query! I have a user exit variable in the query and I believe I can use this user exit variable to show the information message on the varable screen. When we run the que

  • Is it worth it to update to 14.2.A.0.290?

    Hi Everyone, I live in The Netherlands and just today got the notification from the Sony PCC about the 14.2.A.0.290  update. So far, in 4.2.2 everything is working super stable with no bugs, and i can't help but be worried about updating. I see so ma

  • ORA 0655, PLS 00201 identifier sys.dbms_repcat_utl2@tdr1.world

    I have created a repgroup CAROLINE and I get an error when I try to add a master site to it.The master definition site is on v 8.1.7.0.0.(tammy sid) and the master site (pony sid) on v 8.0.6.3.0. The error I get is : ORA-06550: line 1, column 7: PLS-

  • Calendar events not being sent immediately.....finding out when I created an event.

    I recently created a calendar event on my iPhone 5.  I invited an attendee who received the event too late (approximately 36 hours later).  Is there a way to verify and view when I created the event?  Also, is this a common problem?  Why would this h