Skip to content

Instantly share code, notes, and snippets.

@seagalputra
Created March 21, 2020 13:46
Show Gist options
  • Save seagalputra/8117c494252947e99920583d26df9c8b to your computer and use it in GitHub Desktop.
Save seagalputra/8117c494252947e99920583d26df9c8b to your computer and use it in GitHub Desktop.
Example of Builder Pattern using TypeScript
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()
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
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