Java Design pattern Hundred cases-builder mode

Source: Internet
Author: User

The source of this article see: Https://github.com/get-set/get-designpatterns/tree/master/builder

Builder pattern uses multiple simple objects to construct a complex object step-by-stage, and this type of design pattern belongs to the creation pattern. Build mode separates the internal components of a complex object from the creation of the object itself, making it more flexible to assemble complex objects.

Genteel words should not say more, in fact, this model is quite common:
* For example, when we set the mobile phone package, whether it is the choice or the telecommunications company configuration, usually a package includes: how many minutes of the local telephone, how many text messages, how much g of the province and the province outside the flow, and so on, these usually have, but the specific choice of how much can be freely paired.
* For example, when we play online games to create a task, to choose the occupation, color, hairstyle, as well as the game to the role of their equipment, to configure hats, shoulders, capes, tops, trousers, shoes and so on, as well as a series of accessories, more than 10 boxes everyone is the same, the difference is what kind of equipment to put in.

Example

Take the example of the configuration of the online characters mentioned earlier:
When we create a game task, we must fill in the Task name, choose a career or race, and then we can configure the role of hair, hair color, weapons, armor and so on, of course, the following may be based on occupation or race randomly assigned.

The first is the character's hairstyle, hair color, weapons, armor, and Occupation:

hairtype.java

public enum hairtype {    bald ("BALD"),  short ("short"),  CURLY (" Curly "),  long_straight (" Long straight "),  long_curly (" long curly ");     Private string title;    hairtype (String title)  {         this.title = title;    }    @ Override    public string tostring ()  {         return title;    }} 

Haircolor.java

Public enum Haircolor {white, BLOND, RED, BROWN, BLACK;    @Override public String toString () {return name (). toLowerCase (); }}

Weapon.java

Public enum Weapon {DAGGER, SWORD, AXE, Warhammer, BOW;    @Override public String toString () {return name (). toLowerCase (); }}

Armor.java

public enum Armor {CLOTHES ("CLOTHES"), Leather ("Leather"), Chain_mail ("CHAIN Mail"), Plate_mail ("PLATE Mail");    Private String title;    Armor (String title) {this.title = title;    } @Override Public String toString () {return title; }}

Profession.java

Public enum Profession {WARRIOR, thief, MAGE, priest;    @Override public String toString () {return name (). toLowerCase (); }}

In the design of the implementation, we refer to "effective Java" second article "when encountering multiple constructor parameters to consider the content in the builder to organize the relationship between classes." Place the builder class inside the role.

hero.java

public final class hero {    private final profession  Profession;    private final string name;    private  final HairType hairType;    private final HairColor  Haircolor;    private final armor armor;    private  final weapon weapon;    private hero (Builder builder)  {         this.profession = builder.profession;         this.name = builder.name;         this.hairColor = builder.hairColor;         this.hairtype = builder.hairtype;        this.weapon =  builder.weapon;        this.armor = builder.armor;    }     // getters     @Override     public string tostring ()  {        ... ...    }     /**     * The builder class.      */    public static class builder {         private final Profession profession;         private final string name;        private  HairType hairType;        private HairColor  haircolor;        private armor armor;         private Weapon weapon;        /**          * Constructor         */         public builder (Profession profession, string name)  {            if  (profession ==  null | |  name == null)  {                 throw new illegalargumentexception ("Profession and name can  not be null ");            }             this.profession = profession;             this.name = name;     &Nbsp;   }        public builder withhairtype ( Hairtype hairtype)  {             this.hairtype = hairtype;             return this;        }         public builder withhaircolor (Haircolor haircolor)  {             this.hairColor = hairColor;             return this;        }         public builder witharmor (Armor armor)  {             this.armor = armor;             return this;        }         public builder withweapon (Weapon weapon)  {             this.weapon = weapon;             return this;         }        public hero build ()  {             return new hero (This);         }    }}

The main content of the builder model is actually in this hero.java the class.

We can see Hero class has subclasses hero.builder , specific hero is done by the builder. You can see has only one build is a constructor for a parameter, so it will only accept this form of creation.

builder is public the . The reason for this is that it is more convenient to have all of the members accessible from within a similar external class.

When used, you can Builder create an instance by defining a series of "Assembly Methods":

Hero Warrior = new Hero.builder (Profession.warrior, "Amberjill"). Withhaircolor (Haircolor.blond). Withhairtype (HairT Ype. long_curly). Witharmor (Armor.chain_mail). Withweapon (Weapon.sword). build ();

Such a "warrior" was born, suddenly a little want to play online games ~

Summarize

The builder pattern is typically applied to separating a complex construct from its representation, so that the same build process can create different representations. The main solution in the software system, sometimes faced with the creation of "a complex object", which is usually composed of the sub-objects of the various parts with a certain algorithm, due to the change of requirements, the complex object of the various parts often face a drastic change, but the algorithm that combines them is relatively stable.

Finally give a little homework to think about using builder mode:
Suppose Zhang three to build room, turn key bag to stay that kind. He found a service provider, said hope to cover five large-roofed, scraping white lite, the configuration of cheap home, talk about the contract, service providers find construction team to build houses, decoration and with cheap furniture. In addition, there is a person called John Doe also found this service provider, said hope to cover a small ocean floor, refined decoration, with solid wood furniture, service providers and found another good at small foreign building construction team to implement.


Java Design Pattern hundred example-builder mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.