lundi 18 janvier 2016

How to implement nested fluent interface?

I have a task to implement fluent interface for a class, which consist of other classes. Let's say we have a class:

class Pizza {
    int price, size;
}
class Foo {
    string name;
    Pizza p1, p2;
}

I would like to use code like:

Foo f = FooBuilder().setName("foo")
        .settingP1().setPrice(5).setSize(1)
        .settingP2().setPrice(2)
        .build();

but I also would like to forbid code like:

Foo f = FooBuilder().setName("foo").setPrice(5);

I thought about a class inherited from FooBuilder which is returned after calling .settingP1() but I am not sure how to do it. Notice that I don't want to write .build() when I ended specifying Pizza object.

Aucun commentaire:

Enregistrer un commentaire