Created
March 21, 2020 13:46
-
-
Save seagalputra/8117c494252947e99920583d26df9c8b to your computer and use it in GitHub Desktop.
Example of Builder Pattern using TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UserAccountBuilder from './useraccount/UserAccountBuilder' | |
import UserAccount from 'useraccount/UserAccount' | |
const user: UserAccount = new UserAccountBuilder() | |
.withFirstName('Dwiferdio Seagal') | |
.withLastName('Putra') | |
.withUsername('seagalputra') | |
.withPassword('password') | |
.withEmail('seagalputra') | |
.build() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserAccount { | |
private firstName: string | |
private lastName: string | |
private username: string | |
private email: string | |
private password: string | |
constructor( | |
firstName: string, | |
lastName: string, | |
username: string, | |
email: string, | |
password: string | |
) { | |
this.firstName = firstName | |
this.lastName = lastName | |
this.username = username | |
this.email = email | |
this.password = password | |
} | |
} | |
export default UserAccount |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UserAccount from './UserAccount' | |
class UserAccountBuilder { | |
private firstName: string = '' | |
private lastName: string = '' | |
private username: string = '' | |
private email: string = '' | |
private password: string = '' | |
constructor() {} | |
public withFirstName(firstName: string): UserAccountBuilder { | |
this.firstName = firstName | |
return this | |
} | |
public withLastName(lastName: string): UserAccountBuilder { | |
this.lastName = lastName | |
return this | |
} | |
public withUsername(username: string): UserAccountBuilder { | |
this.username = username | |
return this | |
} | |
public withEmail(email: string): UserAccountBuilder { | |
this.email = email | |
return this | |
} | |
public withPassword(password: string): UserAccountBuilder { | |
this.password = password | |
return this | |
} | |
public build(): UserAccount { | |
return new UserAccount( | |
this.firstName, | |
this.lastName, | |
this.username, | |
this.email, | |
this.password | |
) | |
} | |
} | |
export default UserAccountBuilder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment