current position:Home>Builder pattern of Java design pattern

Builder pattern of Java design pattern

2022-02-04 16:42:06 Failed face

Builder pattern : Use multiple simple objects to build a complex object step by step , It provides the best way to create objects .

The purpose of the builder mode : Separate the construction of a complex object from its representation , So that the same build process can create different representations .

advantage : Independence of builders , Easy to expand ; Easy to control detail risk .

Example scenario

In game development , hero Hero Represents a character , They work in different occupations Occupation In the form of , For example, you can change to a soldier or a shooter , Soldiers are equipped with long swords 、 Heavy armor , The archer is equipped with a bow 、 Leather .

Let's use the builder mode to create heroes of different classes , In this process, we should pay attention to the difference between the abstract factory pattern and the abstract factory pattern .

Create a hero and equipment interface class :

package com.cc.builder;
​
/**
 *  Hero interface class 
 * @author cc
 * @date 21-12-19 11:48
 */
public interface Hero {
    String name();
}
 Copy code 
package com.cc.builder;
​
/**
 *  Equipment interface class 
 * @author cc
 * @date 21-12-19 0:24
 */
public interface Equip {
    String name();
}
 Copy code 

Then there are the implementation classes of heroes and equipment :

package com.cc.builder;
​
/**
 *  Hero realization class : warrior 
 * @author cc
 * @date 21-12-19 11:57
 */
public class Warrior implements Hero {
    @Override
    public String name() {
        return "Warrior";
    }
}
 Copy code 
package com.cc.builder;
​
/**
 *  Hero realization class : striker 
 * @author cc
 * @date 21-12-19 11:58
 */
public class Shooter implements Hero {
    @Override
    public String name() {
        return "Shooter";
    }
}
 Copy code 
package com.cc.builder;
​
/**
 *  Equipment implementation class : Long sword 
 * @author cc
 * @date 21-12-19 0:03
 */
public class Sword implements Equip {
    @Override
    public String name() {
        return "Sword";
    }
}
 Copy code 
package com.cc.builder;
​
/**
 *  Equipment implementation class : arch 
 * @author cc
 * @date 21-12-19 0:04
 */
public class Bow implements Equip {
    @Override
    public String name() {
        return "Bow";
    }
}
 Copy code 
package com.cc.builder;
​
/**
 *  Equipment implementation class : Heavy armor 
 * @author cc
 * @date 21-12-19 0:29
 */
public class HeavyArmor implements Equip {
    @Override
    public String name() {
        return "Heavy Armor";
    }
}
 Copy code 
package com.cc.builder;
​
/**
 *  Equipment implementation class : Leather 
 * @author cc
 * @date 21-12-19 0:28
 */
public class LeatherArmor implements Equip {
    @Override
    public String name() {
        return "Leather Armor";
    }
}
 Copy code 

Then there is the professional entity class , This class contains information about heroes and equipment :

package com.cc.builder;
​
import java.util.ArrayList;
import java.util.List;
​
/**
 *  Professional entities 
 * @author cc
 * @date 21-12-19 12:00
 */
public class Occupation {
    private List<Equip> equips = new ArrayList<>();
    private Hero hero;
​
    public Occupation(Hero hero) {
        this.hero = hero;
    }
​
    //  Add equipment 
    public void addEquip(Equip equip) {
        equips.add(equip);
    }
​
    //  Display information 
    public void showInformation() {
        System.out.println("Hero:" + hero.name());
        for (Equip equip : equips) {
            System.out.println(equip.name());
        }
    }
}
 Copy code 

Create a career builder class :

package com.cc.builder;
​
/**
 *  Professional builders 
 * @author cc
 * @date 21-12-19 12:04
 */
public class OccupationBuilder {
    //  Build a warrior class 
    public Occupation prepareWarrior() {
        Occupation occupation = new Occupation(new Warrior());
        occupation.addEquip(new Sword());
        occupation.addEquip(new HeavyArmor());
        return occupation;
    }
​
    //  Build a shooter class 
    public Occupation prepareShooter() {
        Occupation occupation = new Occupation(new Shooter());
        occupation.addEquip(new Bow());
        occupation.addEquip(new LeatherArmor());
        return occupation;
    }
}
 Copy code 

Test it :

package com.cc.builder;
​
public class Main {
    public static void main(String[] args) {
        OccupationBuilder occupationBuilder = new OccupationBuilder();
        {
            Occupation occupation = occupationBuilder.prepareWarrior();
            occupation.showInformation();
        }
        System.out.println("");
        {
            Occupation occupation = occupationBuilder.prepareShooter();
            occupation.showInformation();
        }
    }
}
 Copy code 

result :

Hero:Warrior
Sword
Heavy Armor
​
Hero:Shooter
Bow
Leather Armor
 Copy code 

Builder pattern summary

Let's go back to our introduction to the builder model at the beginning of the above

 The builder pattern uses multiple simple objects to build a complex object step by step , It provides the best way to create objects .
​
 The purpose of the builder mode : Separate the construction of a complex object from its representation , So that the same build process can create different representations .
​
 advantage : Independence of builders , Easy to expand ; Easy to control detail risk .
 Copy code 
  • Our goal is to get a professional object , A single hero or equipment is only a part of this class , With the help of the builder model , We combine various simple objects into a complex object , The caller does not need to care about the specific creation process of the object , You only need to know one calling function 、 Object name or type
  • In the test module, you can see , Same build process , You can create a specific representation of a warrior or shooter
  • Independent and easy to expand , When we have new needs , Create a new builder class to , Basically no need to modify the original code . As in the example , We want to create a mage class , Can be in OccupationBuilder Add functions to the professional builder class , You can also create a new MasterOccupationBuilder.

The difference between builder pattern and abstract factory

In the previous article Java Factory mode of design mode in , We use all the soldiers in the game 、 An example of a shooter , In the process of learning the builder model , It's easy to confuse it with abstract factories , In fact, the difference between them is quite obvious , A closer look at the code of both shows that , In the abstract factory , Each factory function can create an object , They produce multiple products ; And the builder model , It is the sum of all creation functions that can implement an object , Corresponds to the... Described at the beginning : The builder pattern uses multiple simple objects to build a complex object step by step .

Builder pattern and usage scenario of abstract factory

Abstract factory : A series of related product objects can be combined to work , For example, a calculator that supports addition, subtraction, multiplication and division , Every function ( Add, subtract, multiply and divide ) Can be taken out separately , But in order to produce calculator products , Combine their product families by abstracting factories , We produce a calculator , You can have all the functions of addition, subtraction, multiplication and division .

builder : The car is a very complex object , It's through the wheel 、 body 、 Car door 、 Engine and other parts are assembled , A single component makes no sense , Assembling into an object is the goal .

Therefore, the builder mode is mainly used to create a scene of complex objects step by step , Focus on the details of the build process ; The abstract factory is used to create a series of products , Don't care about the build process , Only care about what factory it is produced by .

copyright notice
author[Failed face],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/02/202202041642033865.html

Random recommended