Builder pattern: The main implementation is to create a composite object, and the final object will be merged from several base classes. Different from the previous pattern, the previous factory pattern is the result of the pursuit of creation,
The several classes used for synthesis here are the focus of use, in order to assemble a more complex object.
// create a human var Human = function ( param ) { // Skill this.skill = param && param.skill || 'secret'; // hobby this.hobby = param && param.hobby || 'secret'; }; // human prototype method Human.prototype = { getSkill: function () { return this.skill; }, setSkill: function ( skill) { this.skill = skill; } }; // The creation details of the builder pattern, which is composed of multiple classes // instantiate the name class var Named = function ( name ) { var that = this; // Constructor, the constructor parses the first and last name of the name (function (name , that) { that.wholeName = name; if( name.indexOf(' ')>-1 ){ that.FirstName = name.slice( 0 , name.indexOf(' ') ); that.LastName = name.slice( name.indexOf(' ') ); } })( name , that) }; // instantiate the job class var Work = function ( work) { var that = this; // Constructor, the constructor parses the first and last name of the name (function (work , that) { switch( work ){ case 'code': that.work = 'engineer'; that.workDescript = 'Indulge in programming every day'; break; case 'teach': that.work = 'teacher'; that.workDescript = 'Sharing is also a joy'; break; } })( work , that) }; Work.prototype.changeWork = function (work) { this.work = work; }; Work.prototype.changeDes = function ( sentece) { this.workDescript = sentece; }; /* create a member Parameter name: name Parameter work: desired position Combining the above two classes into a class with composite requirements is simply to dissect a complex class into small classes, which is equivalent to decoupling the code*/ var Person = function ( name , work ) { var _person = new Human(); _person.name = new Named( name ); _person.work = new Work( work ); return _person; }; // instantiate var p = new Person( 'he he' , 'code' ); console.log( p.skill ); p.setSkill('playing the piano'); console.log( p.getSkill() ); console.log( p.work.work ); console.log( p.work.workDescript ); p.work.changeWork( 'no coding!no Life' ); console.log( p.work.work );