当前位置:网站首页>4. creator mode

4. creator mode

2022-06-12 10:13:00 A man who is rubbed on the ground by math every day

4. Creator mode ( Frequency of use :**)

1. The definition of builder pattern

The builder pattern separates the components themselves from their assembly process , Focus on how to create a complex object with multiple components step by step , The user only needs to specify the type of the complex object to get the object , Without knowing the details of its internal structure .

  • Builder pattern : Separate the construction of a complex object from its representation , So that the same build process can create different representations .

The definition of builder pattern

Separate the client from the creation process of complex objects containing multiple parts , The client does not need to know the internal components and assembly of complex objects , You just need to know the type of builder you need

Focus on how to create a complex object step by step , Different builders define different creation processes

2. The structure of the builder model

image-20211110202031975

3. The builder pattern includes the following 4 A character :

  • Builder( Abstract builder )

  • ConcreteBuilder( Specific builder )

  • Product( product )

  • Director( commander ): Command which product to create

4. The realization of builder mode

  • Typical complex object class code :

    public class Product {
          
    	private String partA; // Define the components , Components can be of any type , Including value types and reference types 
    	private String partB;
    	private String partC;
    
    	//partA Of Getter Methods and Setter Method ellipsis 
    	//partB Of Getter Methods and Setter Method ellipsis 
    	//partC Of Getter Methods and Setter Method ellipsis 
    }
    
  • Typical Abstract builder class code :

    public abstract class Builder {
          
        // Create a product object 
       protected Product product=new Product();
        public abstract void buildPartA();
        public abstract void buildPartB();
        public abstract void buildPartC();
    	
        // Return product object 
        public Product getResult() {
          
            return product;
        }
    }
    
  • Typical concrete builder class code :

    public class ConcreteBuilder1 extends Builder{
          
        public void buildPartA() {
          
            product.setPartA("A1");
        }
    
        public void buildPartB() {
          
            product.setPartB("B1");
        }
    
        public void buildPartC() {
          
            product.setPartC("C1");
        }
    }
    
  • Typical conductor class code :

    public class Director {
          
        private Builder builder;
    	
        public Director(Builder builder) {
          
            this.builder=builder;
        }
    	
        public void setBuilder(Builder builder) {
          
            this.builder=builer;
        }
    	
        // Product construction and assembly methods 
        public Product construct() {
          
            builder.buildPartA();
            builder.buildPartB();
            builder.buildPartC();
            return builder.getResult();
        }
    }
    
  • Customer class code snippet :

    ……
    Builder builder = new ConcreteBuilder1(); // It can be realized through the configuration file 
    Director director = new Director(builder);
    Product product = director.construct();
    ……
    

5. Example

A game software company decided to develop a multiplayer online game based on role-playing , Players can play a specific role in the virtual world in the game , Characters according to different game plots and Statistics ( For example, power 、 magic 、 Skills, etc ) Have different abilities , Characters will also have more powerful abilities as they upgrade . As an important part of the game , Need to design game characters , And with the upgrade of the game, new characters will be added . Through analysis, we found that , The game character is a complex object , It contains gender 、 Face and other components , Different types of game characters , Its gender 、 Person's face 、 clothing 、 Hair style and other external characteristics are different , for example “ The angel ” With a beautiful face and long hair with a shawl , And wearing a white skirt ; and “ Devil ” Extremely ugly , Keep a bald head and wear a dazzling black dress . No matter what kind of game character , Its creation steps are similar , You need to create its components step by step , Then assemble the components into a complete game character . Now use the builder mode to realize the creation of game characters .

image-20211110203814760

The sample code

(1) Actor: Game characters , Act as a complex product object

(2) ActorBuilder: Game character builder , Act as an abstract builder

(3) HeroBuilder: Hero character builder , Act as a concrete builder

(4) AngelBuilder: Angel character builder , Act as a concrete builder

(5) DevilBuilder: Demon character builder , Act as a concrete builder

(6) ActorController: Character controller , Act as a commander

(7) Client: Client test class

Results and Analysis

If you need to change the role builder , Just modify the configuration file

When a new role builder needs to be added , Just add the concrete character builder as a subclass of the abstract character builder , Then modify the configuration file , The original code does not need to be modified , Fully comply with the opening and closing principle

<?xml version="1.0"?>
<config>
    <className>designpatterns.builder.AngelBuilder</className>
</config>

6. Omit Director

Omit Director class ( Combine complex products with the process of creating products ( Static methods ) Embedded in the abstract Creator ,)

  • Abstract Creator
public abstract class ActorBuilder {
    
    protected static Actor actor = new Actor();
	
    public abstract void buildType();
    public abstract void buildSex();
    public abstract void buildFace();
    public abstract void buildCostume();
    public abstract void buildHairstyle();
 
    public static Actor construct(ActorBuilder ab) {
    
        ab.buildType();
        ab.buildSex();
        ab.buildFace();
        ab.buildCostume();
        ab.buildHairstyle();
        return actor;
    }
}

Embed the commander in the abstract factory

  • Usage method
……
ActorBuilder ab;
ab = (ActorBuilder)XMLUtil.getBean();
		
Actor actor;
actor = ab.construct();
……

7. The introduction of hook method

Hook method (Hook Method): The return type is usually boolean type , The method name is generally isXXX()

public abstract class ActorBuilder {
    
    protected Actor actor = new Actor();
	
    public abstract void buildType();
    public abstract void buildSex();
    public abstract void buildFace();
    public abstract void buildCostume();
    public abstract void buildHairstyle();
	
    // Hook method 
public boolean isBareheaded() {
    
        return false;
    }
	
    public Actor createActor() {
    
        return actor;
    }
}
public class DevilBuilder extends ActorBuilder {
    
	public void buildType() {
    
		actor.setType(" Devil ");
	}

	public void buildSex() {
    
		actor.setSex(" demon ");
	}

	public void buildFace() {
    
		actor.setFace(" Ugly ");
	}

	public void buildCostume() {
    
		actor.setCostume(" Black ");
	}

	public void buildHairstyle() {
    
		actor.setHairstyle(" Bareheaded ");
	}

                  // Covering hook method 
	public boolean isBareheaded() {
    
		return true;
	}	
}
public class ActorController {
    
    public Actor construct(ActorBuilder ab) {
    
        Actor actor;
        ab.buildType();
        ab.buildSex();
        ab.buildFace();
        ab.buildCostume();
        // The hook method is used to control the construction of products 
        if(!ab.isBareheaded()) {
    
            ab.buildHairstyle();
        }
        actor=ab.createActor();
        return actor;
    }
}

8. Advantages and disadvantages

  • advantage

The client doesn't have to know the details of the product's internal composition , Decouple the product itself from the product creation process , It enables the same creation process to create different product objects

Every concrete builder is relatively independent , It has nothing to do with other specific builders , So it's easy to replace specific builders or add new ones , Easy to expand , Comply with opening and closing principle

You can control the product creation process more precisely

  • shortcoming

The products created by the builder model generally have more in common , Its components are similar , If there is a big difference between products , Not suitable for builder mode , Therefore, its scope of use is limited

If the internal changes of the product are complex , You may need to define many concrete builder classes to implement this change , It makes the system very large , It increases the understanding difficulty and operation cost of the system

9. Applicable environment of mode

  1. The product objects that need to be generated have complex internal structures , These product objects usually contain multiple member variables

  2. The properties of the product objects that need to be generated depend on each other , You need to specify its build order

  3. The creation of an object is independent of the class that created it . The commander class was introduced in the builder pattern , Encapsulates the creation process in the commander class , Not in the builder and customer classes

  4. Isolate the creation and use of complex objects , And allow the same creation process to create different products

原网站

版权声明
本文为[A man who is rubbed on the ground by math every day]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010527414894.html