Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Value-object có hành động #19

Closed
tuananhhedspibk opened this issue Sep 20, 2021 · 0 comments
Closed

Value-object có hành động #19

tuananhhedspibk opened this issue Sep 20, 2021 · 0 comments

Comments

@tuananhhedspibk
Copy link
Owner

Với value-object thì yếu tố quan trọng nhất đó là định nghĩa được một "hành động". Lấy ví dụ về "Money Value-Object".

Với tiền thì sẽ có thuộc tính quan trọng đó là "số lượng" và "đơn vị" ($, ...).

class Money {
  private readonly number amount;
  private readonly string currency;

  constructor(number amount, string currency) {
    this.amount = amount;
    this.currency = currency;
  }
}

Value-Object không chỉ đơn thuần chứa dữ liệu mà nó còn có thể có thêm các methods khác. Ví dụ "tiền" ở trên, ta có thể thêm method Add

class Money {
  private readonly number amount;
  private readonly string currency;

  constructor(number amount, string currency) {
    this.amount = amount;
    this.currency = currency;
  }

  public add(Money args) {
     return new Money(this.amount + args.amount, currency);
  }
}

Vì Value-Object là không thể thay đổi nên ở method Add chúng ta trả về một instance mới. Kết quả trả về sẽ được đưa vào một biến mới.

const money = new Money(1000, "$")
const allowance = new Money(2000, "$")

const result = money.add(allowance);

Xử lí ở trên hoàn toàn tương tự với xử lí tính toán cho các kiểu dữ liệu nguyên thuỷ.

const str1 = "str1";
const str2 = "str2";

const res = str1 + str2;

Những phương thức không được định nghĩa: ở trên ta có phương thức thêm tiền được định nghĩa nhưng phương thức nhân tiền lại không được định nghĩa. Khi đó trong phần định nghĩa của value-object ta chỉ đưa ra function signature mà thôi.

class Money {
  public Money multiply(Money args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant