Explicación del patrón Builder y ejemplo

En este artículo, vamos a explicar la finalidad de Builder.

¿QUÉ ES BUILDER?

Builder es un patrón, es decir, una manera de hacer las cosas. Concretamente, nos permite realizar el encadenamiento de sus métodos (por ejemplo los setters) en la misma declaración del objeto.

¿PARA QUE SE USA BUILER?

Para construir objetos, realmente ya sabemos que existen los constructores. Si el constructor tiene argumentos, podremos construirlos desde el propio constructor. En cambio, si está vacío, deberemos de añadirle los valores mediante a setters.

Builer, por decirlo así combina la creación de un objeto con los setters pero de una manera diferente a los constructores. Dándole una verbosidad a todo esto. Y nace con la finalidad de disminuir la complejidad, otorgándole al código una mejor legibilidad, claridad y compresibilidad.

EJEMPLO DE BUILER CON JAVA

EMPLOYEE.JAVA

Primeramente creamos la clase Employee con sus atributos, un constructor con todos los parámetros y finalmente los getters y setters.

EMPLOYEEBUILDER.JAVA

Creamos los atributos, el constructor vacío, setters y el build que creará el objeto

MAIN.JAVA

En el Main, ahora creamos dos objetos y si os fijáis, utilizando la “verbosera” de setters y finalmente encadenando con build podemos utilizar la especie de constructor que acabamos de construir.

RESULTADO:

Espero que os haya gustado. ¡Un saludo javeros!

66 comentarios

  1. Una pregunta, cual es la ventaja de hacerlo con este patrón? Ya que hay que escribir más código. La verdad no entiendo

    • admin

      15 diciembre, 2020 a las 16:29

      Buenas tardes Henry,

      Te dejo un párrafo sacado de la Wikipedia en el que me apoyo para explicartelo mejor:

      Los patrones de diseño son unas técnicas para resolver problemas comunes en el desarrollo de software y otros ámbitos referentes al diseño de interacción o interfaces.

      Un patrón de diseño resulta ser una solución a un problema de diseño. Para que una solución sea considerada un patrón debe poseer ciertas características. Una de ellas es que debe haber comprobado su efectividad resolviendo problemas similares en ocasiones anteriores. Otra es que debe ser reutilizable, lo que significa que es aplicable a diferentes problemas de diseño en distintas circunstancias.

      Con ello, nos referimos que es una manera una tecnica mediante a la cual poder resolver determinados problemas durante el desarrollo. Aunque esto no significa que sea ni la única ni la mejor mejor manera de realizar las tareas. Un saludo

  2. Hi there, You have done an excellent job. I’ll
    certainly digg it and personally recommend to my friends.
    I am sure they’ll be benefited from this web site.

  3. Hi to all, because I am in fact eager of reading this web site’s post to be
    updated daily. It includes pleasant data.

  4. I got this web page from my pal who shared with me regarding this web page and now this time
    I am visiting this web page and reading very informative content at this place.

  5. I couldn’t resist commenting. Very well written!

    Also visit my page: Arctos Portable Air Conditioner

  6. Hello, this weekend is pleasant in support of me, since this time i am reading this great educational piece of writing here at my
    residence.

    my web page – Keto Max XR Reviews

  7. Howdy! This post couldn’t be written any better!

    Reading this post reminds me of my old room mate! He always kept chatting about this.
    I will forward this article to him. Fairly certain he will have a
    good read. Many thanks for sharing!

    My page … SynoGut Review; http://Www.Koan.At,

  8. I’m gone to convey my little brother, that he
    should also pay a visit this blog on regular basis to take updated from newest gossip.

    Review my web page … Primiene Revitalizing Moisturizer

  9. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is important and everything.

    However imagine if you added some great graphics or video clips to
    give your posts more, “pop”! Your content is excellent but with images and videos, this site could undeniably be one of the
    most beneficial in its field. Excellent blog!

  10. Spot on with this write-up, I seriously believe that this website needs a lot more attention.
    I?ll probably be back again to see more, thanks for the info!

    Also visit my web blog :: Luiresse Skin Care

  11. Thanks for every one of your hard work on this web page. Gloria take interest in participating in internet research and it’s really easy to understand why.
    Almost all know all of the lively method you provide effective suggestions through this website and as well as cause response
    from visitors on the article while our own child has been learning a
    whole lot. Take advantage of the rest of the year. You
    have been performing a first class job.[X-N-E-W-L-I-N-S-P-I-N-X]I’m extremely impressed along with your writing
    skills as smartly as with the structure on your blog.
    Is this a paid topic or did you customize it yourself?
    Either way stay up the nice quality writing, it is rare to look a nice weblog like this one nowadays.

    Also visit my blog post :: Pure Keto Burn Pills

  12. We are a gaggle of volunteers and opening a new
    scheme in our community. Your website offered us with valuable information to work on. You’ve performed an impressive activity and our whole community might be grateful to you.

    my homepage … Sparkling CBD

  13. Very nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed browsing your blog posts.
    After all I’ll be subscribing to your rss feed
    and I hope you write again soon!

    Feel free to visit my webpage :: VikingXL Keto

  14. It’s going to be ending of mine day, but before ending I am reading this great paragraph to improve
    my knowledge.

    My web page ColonBroom Reviews (koan.at)

  15. Link exchange is nothing else but it is just placing the other person’s website
    link on your page at suitable place and other person will also do same in support of you.

  16. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your blog?
    My blog is in the very same area of interest as yours and
    my users would really benefit from a lot of the information you present here.
    Please let me know if this okay with you. Many thanks!

  17. I couldn?t refrain from commenting. Well written!

    My homepage :: Infinuity CBD

  18. Great blog! Is your theme custom made or did you download
    it from somewhere? A theme like yours with a few simple tweeks would really make my blog
    jump out. Please let me know where you got your design. Many thanks

    Look into my web blog Bio Shed Keto

  19. When someone writes an post he/she retains the idea of a user in his/her
    brain that how a user can understand it. Therefore that’s why this article is perfect.
    Thanks!

  20. My family every time say that I am wasting my time here at web, except I know I am
    getting experience daily by reading thes pleasant posts.

    my page :: Niva CBD Gummies Cost (Noble)

  21. Hey! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

    My web site … Wawza Apple Cider Gummies

  22. Lovely just what I was looking for. Thanks to the author for taking his clock time on this one.

    Feel free to visit my web page Modern Belle Hydrofirm

  23. For the reason that the admin of this site is working,
    no uncertainty very rapidly it will be renowned, due to its quality contents.

    Also visit my blog; Vigor Max Male Enhancement, http://www.fotosombra.com.br/agenda/userinfo.php?uid=881793,

  24. I don’t commonly comment but I gotta admit thanks for the
    post on this perfect one :D.

    My blog; Wild Lean Keto Boost Ingredients

  25. I consider something truly interesting about your website so I saved to
    fav.

    Also visit my page; Moscatcher Reviews

  26. I really like your blog.. very nice colors & theme. Did you design this
    website yourself or did you hire someone to
    do it for you? Plz reply as I’m looking to design my own blog and
    would like to know where u got this from. many thanks

    Here is my website; Alpha Edge Pills Review – conservadores.prosite.ws,

  27. What’s up, everything is going sound here and ofcourse every one is sharing data, that’s in fact fine, keep up writing.

    Also visit my website Eagle Hemp CBD Gummies

  28. I drop a leave a response when I especially enjoy a post on a site or I have something to valuable to contribute to the discussion. It’s a result of the passion displayed in the post I looked at.

    And after this article Explicación del patrón Builder y ejemplo – Java desde 0.
    I was moved enough to drop a thought 😉 I do have 2 questions for you if you tend not to
    mind. Could it be only me or does it look like some of the comments
    appear like they are written by brain dead folks?
    😛 And, if you are posting on additional social sites, I would like to follow anything fresh you
    have to post. Would you list all of your communal sites like your Facebook page,
    twitter feed, or linkedin profile?

    Feel free to visit my web-site :: Infinuity CBD – http://www.fotosombra.com.br/agenda/userinfo.php?uid=882849,

  29. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. In my view, if
    all web owners and bloggers made good content as
    you did, the web will be much more useful than ever before.

  30. Very soon this web page will be famous amid all blogging and site-building visitors, due to it’s
    fastidious content

    Take a look at my web-site: Niva CBD Gummies (http://forum.adm-tolka.ru/)

  31. Heya just wanted to give you a brief heads up and let you know a few of The Skin Company Cream Reviews images aren’t
    loading correctly. I’m not sure why but I think its a linking issue.
    I’ve tried it in two different internet browsers and both show the
    same outcome.

  32. Attractive section of content. I just stumbled upon your site and in accession capital to assert that I acquire actually enjoyed account your blog posts.
    Any way I will be subscribing to your feeds and even I achievement you
    access consistently fast.

    My site :: Ketoroll

  33. Thanks a bunch for sharing this with all of us you really understand what you are talking approximately!
    Bookmarked. Kindly additionally consult with my site =).
    We will have a link exchange arrangement among us

  34. What’s Happening i’m new to this, I stumbled upon this I’ve found It
    positively helpful and it has aided me out loads.
    I am hoping to contribute & aid different customers like its helped me.
    Good job.

    Here is my web site: Vialis Male Enhancement Pills (Lino)

  35. With havin so much content do you ever run into any
    issues of plagorism or copyright infringement? My blog has a lot of exclusive content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over
    the web without my agreement. Do you know any methods
    to help protect against content from being ripped off?
    I’d really appreciate it.

  36. Rattling clear web site, appreciate it for this post.

    Here is my web-site Keto Secret Keto

  37. It’s awesome to pay a visit this site and reading the views of all mates
    on the topic of this article, while I am also keen of
    getting knowledge.

  38. I visited many web pages except the audio feature
    for audio songs existing at this web page is genuinely marvelous.

    My web site; Optimum Keto Reviews

  39. Yeah bookmaking this wasn’t a risky conclusion great post!

    my web-site – Keto Incinerate Diet

  40. Awesome! Its truly awesome piece of writing, I have got much clear idea
    on the topic of from this post.

    Here is my web blog Insights CBD Oil

  41. Great post. I used to be checking continuously this blog and I’m inspired!

    Very useful info particularly the last section 🙂 I take
    care of such info much. I was looking for this particular info for a very long time.
    Thank you and best of luck.

    Here is my page; http://www.comptine.biz

  42. I’ve recently started a blog, the info you provide
    on this site has helped me greatly. Thank you for all of your time &
    work.

    Here is my web blog; Luiresse Skin Care

  43. I loved as much as you’ll receive carried out right here.
    The sketch is tasteful, your authored material stylish. nonetheless, you command get got an edginess over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same nearly a lot
    often inside case you shield this increase.

    Also visit my web blog – Natural Burn Keto Pills, Vanessa,

  44. What a data of un-ambiguity and preserveness of precious knowledge about unexpected emotions.

    Feel free to visit my site – Molten Keto

  45. Hi there just wanted to give you a quick heads up.
    The words in your article seem to be running off the screen in Firefox.

    I’m not sure if this is a format issue or something to do
    with web browser compatibility but I figured I’d post to let you
    know. The style and design look great though! Hope you get the
    issue solved soon. Kudos

  46. I do not know whether it’s just me or if everybody else
    encountering issues with your blog. It appears as
    if some of the written text in your posts are running off
    the screen. Can somebody else please comment and
    let me know if this is happening to them as well?

    This may be a issue with my browser because I’ve
    had this happen previously. Kudos

    My blog post; Biodermeux Reviews (http://Www.Cruzenews.Com)

  47. Greetings from Los angeles! I’m bored to death at work so I decided to browse your website on my iphone during lunch break.
    I enjoy the knowledge you present here and can’t wait to take a look when I get home.

    I’m surprised at how fast your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, awesome site!

    Feel free to surf to my homepage: Keto Incinerate Review

  48. It is in point of fact a nice and useful piece of information. I’m satisfied that you simply shared this
    useful information with us. Please stay us up to date like this.
    Thank you for sharing.

    Stop by my web-site; IceHouse Portable AC Reviews

  49. I believe what you posted made a great deal of sense.
    However, think on this, what if you added a little content?
    I mean, I don’t want to tell you how to run your blog, however suppose you added a title to possibly grab a person’s attention? I mean Explicación del
    patrón Builder y ejemplo – Java desde 0 is kinda vanilla.

    You could glance at Yahoo’s home page and note how they write post titles to grab viewers to
    open the links. You might add a related video or a pic or two to get
    people excited about what you’ve got to say.
    Just my opinion, it would bring your blog a little livelier.

    my blog post – Arctic Box AC

  50. thank you for all your efforts that you have put in this.
    Very interesting info.

    Feel free to surf to my blog post … Molten Keto Review

  51. Pretty nice post. I just stumbled upon your blog and
    wished to say that I have truly enjoyed browsing your
    blog posts. After all I’ll be subscribing to your rss feed and I hope you write
    again very soon!

  52. I will right away grab your rss as I can not to find your email subscription link or
    e-newsletter service. Do you have any? Please let me understand so
    that I could subscribe. Thanks.

    my web site :: Insights CBD Review (http://www.nazisociopaths.org)

  53. hello there and thank you for your info ? I have certainly picked up something new from right here.
    I did however expertise a few technical points using this web site, as I experienced to reload
    the website a lot of times previous to I could get it to load correctly.
    I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement
    in google and can damage your high-quality score if advertising and marketing with Adwords.

    Well I?m adding this RSS to my email and can look out for a lot more of your respective exciting content.
    Make sure you update this again soon..

    My blog … Aizen Power Male Enhancement

  54. Hello would you mind stating which blog platform you’re working with?
    I’m going to start my own blog soon but I’m having a tough time making
    a decision between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your layout seems different
    then most blogs and I’m looking for something unique.
    P.S My apologies for getting off-topic but I had to ask!

  55. Wow, amazing weblog format! How long have you been blogging for?
    you made running a blog look easy. The overall look of
    your website is great, let alone the content!

    Here is my blog post; Keto Incinerate Reviews

  56. I have been reading out some of your articles and i
    must say pretty clever stuff. I will definitely bookmark your site.

    My website Hydrofirm Review

  57. WOW just what I was searching for. Came here by searching for my

  58. I’d always want to be update on new posts on this site, saved to bookmarks!

    Here is my site :: mtasa-forum.com

  59. Have you ever considered publishing an ebook or guest authoring on other blogs?
    I have a blog based on the same topics you discuss and would
    really like to have you share some stories/information. I know my readers would
    value your work. If you are even remotely interested, feel free
    to shoot me an e-mail.

    Also visit my site; http://bogema.anapacenter.info/modules.php?name=Your_Account&op=userinfo&username=RigginsVera

  60. Really when someone doesn’t understand after that its up to other people that they will
    assist, so here it happens.

    Also visit my homepage; Ilok Air Conditioner

  61. My family members always say that I am wasting my time here at
    net, however I know I am getting knowledge everyday by reading such nice content.

  62. I blog often and I genuinely appreciate your information. The article has truly peaked my interest.
    I am going to bookmark your site and keep checking for new details about once a week.
    I subscribed to your Feed too.

  63. If you desire to increase your knowledge just
    keep visiting this web page and be updated with the
    newest news update posted here. asmr https://app.gumroad.com/asmr2021/p/best-asmr-online asmr

  64. We’re a gaggle of volunteers and starting a brand new scheme in our community.
    Your site offered us with helpful info to work on. You have
    performed a formidable job and our entire community
    will likely be grateful to you. quest bars http://bitly.com/3jZgEA2 quest
    bars

  65. hello!,I love your writing very much! share we keep in touch more about
    your article on AOL? I need an expert on this house to resolve my
    problem. Maybe that’s you! Taking a look ahead to look you.

    Visit my webpage getting treatment

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.

Cerrar