[Design Pattern] Value Object

Problem to Solve

Reparesent a value that is immutable and distinct from other objects based on its properties rather than its identity.

 

Solution

Create a class where instances are considered equal if all their properties are equals and ensure the object is immutable.

 

Use cases

Representing complex data types like money, coordinates, or dates.

 

Code

Class Money {
    constructor(amount, currency) {
        this.amount = amount
        this.currency = currency
        // Freeze the object to make it immutable
        Object.freeze(this)
    }
    
    equals(other) {
        return other instanceof Money &&
            this.amount === other.amount &&
            this.currency = other.currency;
    }
}

 

posted @ 2024-08-14 14:52  Zhentiw  阅读(1)  评论(0编辑  收藏  举报