Builder Design Pattern

Run Settings
LanguageJava
Language Version
Run Command
class Main { public static void main(String[] args) { // ادخال جميع القيم Employee employee1 = new Employee.Builder(1, "Hassan", "Brahimi") .setAddress("Address") .setAge(25) .setPhone("123") .build(); System.out.println("Employee 1 : " + employee1.toString()); // ادخال العمر فقط Employee employee2 = new Employee.Builder(2, "Husam", "Lkarti") .setAge(25) .build(); System.out.println("Employee 2 : " + employee2); // بدون القيم الاختيارية Employee employee3 = new Employee.Builder(3, "Ismail", "Bella") .build(); System.out.println("Employee 3 : " + employee3); } }
public class Employee{ private int id; private String firstName; private String lastName; private int age; private String phone; private String address; // من الافضل ان يكون private public Employee(Builder builder) { this.id = builder.id; this.firstName = builder.firstName; this.lastName = builder.lastName; // البيانات الاختيارية this.age = builder.age; this.phone = builder.phone; this.address = builder.address; } // getters public int getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public String getPhone() { return phone; } public String getAddress() { return address; } @Override public String toString() { return "Employee{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + ", phone='" + phone + '\'' + ", address='" + address + '\'' + '}'; } // هذا الكلاس هو الذي يقوم ببناء كلاس الموظف public static class Builder { private int id; private String firstName; private String lastName; private int age; private String phone; private String address; public Builder(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public Builder setAge(int age) { this.age = age; return this; } public Builder setPhone(String phone) { this.phone = phone; return this; } public Builder setAddress(String address) { this.address = address; return this; } public Employee build() { isValidateEmployeeData(); return new Employee(this); } private boolean isValidateEmployeeData() { //يمكنك التحقق من البيانات المدخلة هنا . return true; } } }
Editor Settings
Theme
Key bindings
Full width
Lines