美文网首页
建造者模式

建造者模式

作者: Q大疯zi | 来源:发表于2018-12-07 11:20 被阅读5次

    直接上代码

    class Dog {
        private static int age;
        private static String name;
        private static String nickName;
        private static String food;
    
        static class Builder {
            private Dog dog;
    
            Builder() {
                dog = new Dog();
            }
    
            Builder setAge(int age) {
                dog.age = age;
                return this;
            }
    
            Builder setName(String name) {
                dog.name = name;
                return this;
            }
    
            Builder setNickName(String nickName) {
                dog.nickName = nickName;
                return this;
            }
    
            Builder setEatFood(String foot) {
                dog.food = foot;
                return this;
            }
    
            void setLookHome() {
                System.out.print("name:" + name + "\n绰号:" + nickName + "\n年龄:" + age + "\n食物:" + food + "\n看家中----");
            }
        }
    }
    
    Dog.Builder builder = new Dog.Builder()
                    .setAge(5)
                    .setEatFood("肉")
                    .setName("小黄")
                    .setNickName("小黄黄");
    
            builder.setLookHome();
    

    运行

    name:小黄
    绰号:小黄黄
    年龄:5
    食物:肉
    看家中----
    

    相关文章

      网友评论

          本文标题:建造者模式

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