Khi một Object có thể được tạo từ nhiều attributes khác nhau thì chúng ta nên consider sử dụng Builder Pattern thay cho Static factories hoặc Constructors . Ví dụ sử dụng Builder Pattern: // Builder Pattern public class NutritionFacts { private final int servingSize ; private final int servings ; private final int calories ; private final int fat ; private final int sodium ; private final int carbohydrate ; public static class Builder { // Required parameters private final int servingSize ; private final int servings ; // Optional parameters - initialized to default values private int calories = 0 ; private int fat = 0 ; private int sodium = 0 ; private int carbohydrate = 0 ; public Builder ( int servingSize , int servings ) { this . servingSize = servingSize ; this . servings = servings ; } public Builder calories ( int val ) { calories = val ; retu...
Ở bài viết này, chúng ta sẽ bàn về cách để tạo Object trong Java. Để tạo mới một Object trong Java thì cách truyền thống là provide một public constructor và sử dụng keyword new ở client. Có một cách khác mà chúng ta nên biết và consider để sử dụng thay cho cách truyền thống đó là provide static factory methods . Vậy ưu điểm và nhược điểm của static factory methods là gì, chúng ta sẽ cùng tìm hiểu trong bài viết này. Cách truyền thống: Provide a public constructor Ví dụ: Class Student.java public class Student { private long id ; private String name ; public Student ( long id , String name ) { this . id = id ; this . name = name ; } } Client có thể tạo instance bằng cách sử dụng new keyword: Student student = new Student ( 1 , "Nguyễn Văn A" ); Sử dụng Static Factory Methods Ví dụ: Class Student.java public class Student { private long id ; private String name ; private Student ( long id , Strin...