七爪源码:在编程世界中如何真正使用 Javascript 中的 Builder 模式

今天,我们将讨论编程中流行的设计模式之一,建造者模式。

在我们开始解释之前,让我们看一下下面的代码


class User {  constructor(firstName, lastName) {    this.firstName = firstName;    this.lastName = lastName;  }}const tonyStark = new User('Tony', 'Stark')

从上面的代码中,我们有一个 User 类,我们创建了 User 对象,然后将它保存在一个变量 tonyStark 中。 这种方法没有任何问题,因为我们只有一个具有两个属性的对象。 但是,如果我们创建一个具有许多需要在对象创建过程中提供的属性的对象呢?

class User {  constructor(firstName, middleName, lastName, suffix, phone, email, isActive, lastSeen) {    this.firstName = firstName;    this.middleName = middleName;    this.lastName = lastName;    this.suffix = suffix;    this.phone = phone;    this.email = email;    this.isActive = isActive;    this.lastSeen = lastSee;  }}const tonyStark = new User('Tony', 'Mc', 'Stark', 'Mr', '+620382931232', 'tonystark@tonystark.com', true, '01-01-2021')const johnDoe = new User('John', 'Mc', 'Doe', 'Mr', '+623123232323', 'johndoe@johndoe.com', true, '02-01-2021')

正如您在上面的代码中看到的,实例化对象的过程变得非常繁琐并且容易出错。 我们需要小心我们提供的参数的顺序,如果我们提供的顺序不正确,这可能会成为应用程序中的错误来源。 我们是人类,人类往往会犯错误。

这就是创建构建器模式的原因。 构建器模式是一种设计模式,旨在通过从表示简化复杂对象的构造来为各种对象创建问题提供灵活的解决方案。

class UserBuilder {  constructor(firstName, middleName, lastName) {    this.firstName = firstName;    this.middleName = middleName;    this.lastName = lastName;  }  setSuffix(suffix) {    this.suffix = suffix;    return this;  }  setPhone(phone) {    this.phone = phone;    return this;  }  setEmail(email) {    this.email = email;    return this;  }  setIsActive(isActive) {    this.isActive = isActive;    return this;  }  setLastSeen(lastSeen) {    this.lastSeen = lastSeen;    return this;  }  build() {    if (!('firstName' in this)) {      throw new Error('First Name is missing')    }    if (!('lastName' in this)) {      throw new Error('Last Name is missing')    }    if (!('phone' in this)) {      throw new Error('Phone is missing')    }    if (!('email' in this)) {      throw new Error('Email is missing')    }    if (!('isActive' in this)) {      throw new Error('isActive is missing')    }    if (!('lastSeen' in this)) {      throw new Error('lastSeen is missing')    }    return new User(this.firstName, this.middleName, this.lastName, this.suffix, this.phone, this.email, this.isActive, this.lastSeen)  }}const tonyStark = new UserBuilder('Tony', null, 'Stark')  .setSuffix('Mr')  .setPhone('620382931232')  .setEmail('tonystark@tonystark.com')  .setIsActive(true)  .setLastSeen('01-01-2021')  .build();const johnDoe = new UserBuilder('John', 'Mc', 'Stark')  .setPhone('623123232323')  .setEmail('johndoe@tonystarkjohndoe.com')  .setIsActive(true)  .setLastSeen('02-01-2021')  .build();

通过使用构建器模式,现在我们可以清楚地看到创建用户实例时发生了什么。 这导致代码易于编写且非常易于阅读和理解。 我们通过仅提供 firstName、middleName 和 lastName 来简化参数。 这不仅使它更容易理解,而且在实例化对象时将人为错误降至最低。 我们甚至在构建器中添加错误处理程序,我们可以指定哪个参数是必需的或可选的。 我们通过链接 setter 方法创建对象,最后调用 build() 方法完成创建对象。

我希望这篇简短的文章可以帮助您理解构建器模式以及何时使用它。


结论

我希望这篇文章能提供信息。 如果您有任何问题,请随时与我联系。

关注七爪网,获取更多APP/小程序/网站源码资源!

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章