美文网首页
Builder Design Pattern

Builder Design Pattern

作者: zheting | 来源:发表于2018-03-22 07:41 被阅读20次
    package com.sheting.design.pattern.demo3;
    
    /**
     * @author SheTing
     * @Time 7:32
     */
    public class Computer {
        //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 Computer(ComputerBuilder builder) {
            this.HDD = builder.HDD;
            this.RAM = builder.RAM;
            this.isGraphicsCardEnabled = builder.isGraphicsCardEnabled;
            this.isBluetoothEnabled = builder.isBluetoothEnabled;
        }
    
        //Builder Class
        public static class ComputerBuilder {
    
            // required parameters
            private String HDD;
            private String RAM;
    
            // optional parameters
            private boolean isGraphicsCardEnabled;
            private boolean isBluetoothEnabled;
    
            public ComputerBuilder(String hdd, String ram) {
                this.HDD = hdd;
                this.RAM = ram;
            }
    
            public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
                this.isGraphicsCardEnabled = isGraphicsCardEnabled;
                return this;
            }
    
            public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
                this.isBluetoothEnabled = isBluetoothEnabled;
                return this;
            }
    
            public Computer build() {
                return new Computer(this);
            }
    
        }
    }
    
    
    package com.sheting.design.pattern.demo3;
    
    /**
     * @author SheTing
     * @Time 7:34
     */
    public class TestBuilderPattern {
    
        public static void main(String[] args) {
            //Using builder to get the object in a single line of code and
            //without any inconsistent state or arguments management issues
            Computer comp = new Computer.ComputerBuilder("500 GB", "2 GB")
                    .setBluetoothEnabled(true)
                    .setGraphicsCardEnabled(true)
                    .build();
        }
    
    }
    
    

    Builder Design Pattern Example in JDK

    • java.lang.StringBuilder#append() (unsynchronized)
    • java.lang.StringBuffer#append() (synchronized)

    相关文章

      网友评论

          本文标题:Builder Design Pattern

          本文链接:https://www.haomeiwen.com/subject/cgeoqftx.html