07 febrero 2014

#{ TIP: Builder Pattern }

0 comentarios

Builder Pattern ejemplo, queda bonito llamar a los constructores así, además se bypassear, los valores por defecto de los métodos (default value parameter) como por ejemplo se puede hacer en otros lenguajes como C++ o ActionScript3 por ejemplo:
void parameterizedMethod(float param1, int param2, bool param3=false);
En JAVA se puede "bypassear" con la siguiente técnica:
public class StudentBuilder
{
    private String _name;
    private int _age = 14;      // this has a default
    private String _motto = ""; // most students don't have one

    public StudentBuilder() { }

    public Student buildStudent()
    {
        return new Student(_name, _age, _motto);
    }

    public StudentBuilder name(String _name)
    {
        this._name = _name;
        return this;
    }

    public StudentBuilder age(int _age)
    {
        this._age = _age;
        return this;
    }

    public StudentBuilder motto(String _motto)
    {
        this._motto = _motto;
        return this;
    }
}
Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
                 .name("Spicoli")
                 .age(16)
                 .motto("Aloha, Mr Hand")
                 .buildStudent();
http://stackoverflow.com/questions/222214/managing-constructors-with-many-parameters-in-java-1-4/222295#222295
 
Buffer de Código | © Design by DheTemplate.com and Theme 2 Blog

Find more free Blogger templates at DheTemplate.com - Daily Updates Free Blogger Templates