0

下面是我的生成器模式类,它生成一个员工对象。

public class Employee {
    // required parameters
    private String HDD;
    private String RAM;

    // optional parameters
    private boolean isGraphicsCardEnabled;
    private boolean isBluetoothEnabled;

    public String getHDD() {
        return HDD;
    }
    public String getRAM() {
        return RAM;
    }
    public boolean isGraphicsCardEnabled() {
        return isGraphicsCardEnabled;
    }
    public boolean isBluetoothEnabled() {
        return isBluetoothEnabled;
    }

    private Employee(EmployeeBuilder builder) {
        this.HDD=builder.HDD;
        this.RAM=builder.RAM;
        this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
        this.isBluetoothEnabled=builder.isBluetoothEnabled;
    }

    public static class EmployeeBuilder {
        private String HDD;
        private String RAM;

        // optional parameters
        private boolean isGraphicsCardEnabled;
        private boolean isBluetoothEnabled;

        public EmployeeBuilder(String hdd, String ram){
            this.HDD = hdd;
            this.RAM = ram;
        }

        public EmployeeBuilder isGraphicsCardEnabled(Boolean isGraphicsCardEnabled){
            this.isGraphicsCardEnabled = isGraphicsCardEnabled;
            return this;
        }

        public EmployeeBuilder isBluetoothEnabled(boolean isBluetoothEnabled){
            this.isBluetoothEnabled = isBluetoothEnabled;
            return this;
        }

        public Employee build(){
            return new Employee(this);
        }
    }

    public static void main(String args[]){
        Employee emp = new Employee.EmployeeBuilder("500", "64").
                isGraphicsCardEnabled(true).
                isGraphicsCardEnabled(true).build();

        System.out.println(emp.HDD);
        System.out.println(emp.getHDD());

    }
}

已设置参数的构建器会很好Abstract Factory [Gamma95, p. 87]。换句话说,客户端可以将这样的 a 传递builder给方法,以使该方法能够为客户端创建一个或多个对象。要启用此用法,您需要一个类型来表示构建器。如果您使用的是 1.5 版或更高版本,则single generic type (Item 26)适用于所有构建器,无论他们正在构建什么类型的对象。

任何人都可以通过一个工作示例为上述段落添加一些亮点。我无法理解上述取自Effective Java - Joshua Bloch的段落。

4

0 回答 0