c ++中有效的java builder习惯用法? [英] effective java builder idiom equivalent in c++?

查看:169
本文介绍了c ++中有效的java builder习惯用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从阅读有效的Java以来​​,这是一个很好的成语。我一直在尝试找到一个类似C ++的类似的东西,并且几乎没有运气。在GoF书中发现的传统建筑模式在我的情况下并不适用。这是一个复杂的对象,它有一个非常混乱的构造函数。以下是Java的一个小型实现。

This is a great idiom I've been using since reading Effective Java. I've been trying to find a C++ equivalent or something similar and have had little luck. The traditional builder pattern found in the GoF book isn't really applicable in my case. It's one complicated object that has a very messy constructor. Below is a small implementation of the Java.

class ComplicatedObject {

    private String field1;
    private String field2;
    private int      field3;

    private ComplicatedObject(Builder builder) {

            this.field1 = builder.myField1;
            this.field2 = builder.myField2;
            this.field3 = builder.myField3;

    }

    public static class Builder {

            private String myField1 = "some default";
            private String myField2 = "some other default";
            private int           myField3 = -1;

            public Builder() { }
            public Builder field1(String val) {
                    this.myField1 = val;
                    return this;
            }
            public Builder field2(String val) {
                    this.myField2 = val;
                    return this;
            }
            public Builder field3(int val) {
                    this.myField3 = val;
                    return this;
            }
            public ComplicatedObject build() {
                    return new ComplicatedObject(this);
            }
    }
    public static void main(final String[] args) {
    //built like this

            ComplicatedObject obj = new ComplicatedObject.Builder().field1("blah").field2("lol").field3(4).build();

    }
}


推荐答案

不仅可以适应C ++,而且还可以从 C ++中修改成语。

Not only can it be adapted to C++ but rather the idiom has been adapted from C++.

我认为第一次听说这个成语是在Java诞生之前。 IIRC Bjarne Stroustrup在C ++第2版中提到这个解释,为什么C ++不需要Smalltalk样式命名参数。

I think the first time I heard of this idiom was before Java came into existence. IIRC Bjarne Stroustrup mentions this in C++ 2nd Edition as an explanation of why C++ does not need Smalltalk style named parameters.

我可以让我的日期错误,但这是大约15年旧版C ++中。

I could have my dates wrong but this is about 15 years old in C++.

编辑:它似乎首先在C ++ (6.5.1)的设计与演进中描述,它被称为命名函数参数

It seems it wad first described in Design and Evolution of C++ (6.5.1) where it was called named function parameters

这篇关于c ++中有效的java builder习惯用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆