Builder mode [Java design mode]

Keywords: Android

Builder mode

android

Builder mode (also called generator design mode):

When the internal data of a class is too complex (usually the class responsible for holding the data, such as VO, PO, Entity...), to create it, you may need to understand the internal structure of the class, and how these things are organized and assembled, which is a mess. At this time, it will increase the learning cost and will be very confusing. At this time, think about what kind of Method to manage the data in this class, how to make it step by step when creating, and the code readability is very good. Don't let me see it. What I want can also be set in very well. This is the application scenario of Builder mode, which can separate the construction and representation of a class.

Look at the example:

class Person {
    private var name: String? = null
    private var age: String? = null
    private var height: String? = null
    private var weight: String? = null
    private var sex: String? = null

    constructor(person: Person){
        this.name=person.name
        this.age=person.age
        this.height=person.height
        this.weight=person.weight
        this.sex=person.sex
    }

    private constructor()

    class Builder {
        private val person: Person = Person()

        fun name(name: String): Builder {
            person.name = name
            return this
        }

        fun age(age: String): Builder {
            person.age = age
            return this
        }

        fun height(height: String): Builder {
            person.height = height
            return this
        }

        fun weight(weight: String): Builder {
            person.weight = weight
            return this
        }

        fun sex(sex: String): Builder {
            person.sex = sex
            return this
        }

        fun build(): Person {
            return Person(person)
        }
    }

    override fun toString(): String {
        return "Person(name=$name, age=$age, height=$height, weight=$weight, sex=$sex)"
    }
}

Call and run results:

class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val build = Person.Builder()
            .age("16")
            .height("199")
            .name("ODP")
            .weight("180")
            .sex("male")
            .build()
        
        Log.e("odp", "p1: $build")
    }
}

 

Be careful:

The parameterless constructor in our Person class is decorated by private, that is to say, when users call it, they can only call it in the way we want (Builder goes to point every property).

Posted by suomynonA on Sun, 10 Nov 2019 12:09:38 -0800