



<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Software Guisho &#187; patrones creacionales</title>
	<atom:link href="http://software.guisho.com/software/patrones-creacionales/feed" rel="self" type="application/rss+xml" />
	<link>http://software.guisho.com</link>
	<description>Hablemos un poco de software con ñ.</description>
	<lastBuildDate>Thu, 10 Nov 2011 22:50:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño</title>
		<link>http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno</link>
		<comments>http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno#comments</comments>
		<pubDate>Fri, 29 May 2009 18:27:10 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[Patrones Creacionales]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[builder pattern]]></category>
		<category><![CDATA[constructor encadenado]]></category>
		<category><![CDATA[fluid interface]]></category>
		<category><![CDATA[interfaces fluídas]]></category>
		<category><![CDATA[patron builder]]></category>
		<category><![CDATA[patron constructor]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[patrones creacionales]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=104</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno&amp;text=Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño&amp;via=lhernandez&amp;related=guishogt"><img align="right" src="http://software.guisho.com/wp-content/plugins//easy-twitter-button/i/buttons/es/tweetn.png" style="border: none;" alt="" /></a></div>
El builder pattern, o patrón de construcción, es uno más de los patrones creacionales de diseño. En términos generales un builder esconde los detalles de la creación de un objeto final que se llama producto. Hay varios métodos para lograr esto, y por ello hay varias &#8220;implementaciones&#8221; de este patrón que en nada coinciden , [...]


Related posts:<ol><li><a href='http://software.guisho.com/singleton-pattern-patrones-de-diseno' rel='bookmark' title='Permanent Link: Singleton Pattern &#8212; Patrones de diseño'>Singleton Pattern &#8212; Patrones de diseño</a></li>
<li><a href='http://software.guisho.com/abstract-factory-pattern-patrones' rel='bookmark' title='Permanent Link: Abstract Factory Pattern &#8211; Patrones'>Abstract Factory Pattern &#8211; Patrones</a></li>
<li><a href='http://software.guisho.com/patrones-de-diseno-factory-pattern' rel='bookmark' title='Permanent Link: Factory Pattern &#8211; Patrones'>Factory Pattern &#8211; Patrones</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno&amp;text=Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño&amp;via=lhernandez&amp;related=guishogt"><img align="right" src="http://software.guisho.com/wp-content/plugins//easy-twitter-button/i/buttons/es/tweetn.png" style="border: none;" alt="" /></a></div>
<p><img class="alignleft size-medium wp-image-117" title="lego" src="http://software.guisho.com/wp-content/uploads/2009/05/lego.jpg" alt="lego" width="300" height="199" /></p>
<p>El builder pattern, o patrón de construcción, es uno más de los patrones creacionales de diseño. En términos generales un builder esconde los detalles de la creación de un objeto final que se llama producto. Hay varios métodos para lograr esto, y por ello hay varias &#8220;implementaciones&#8221; de este patrón que en nada coinciden , salvo en el nombre. El clásico, usado en el GoF es un poco más complejo del que vamos a ver ahora, pero no se asusten, ya tendremos la oportunidad de aprenderlo. En esta ocasión nos vamos a enfocar en un builder que se llaman interfaces fluídas (fluid interfaces).<span id="more-104"></span></p>
<p>Y seguimos con la política de que la mejor manera de entender, y de aprender, es con un ejemplo. Estuve dándole vueltas a un buen caso para ejemplificar y se me ocurrió este: supongamos que vamos a hacer un programa para una empresa que ofrece servicios de web hosting (alojamiento en web). Esta empresa tiene varios planes que ofrecer: tiene un plan personal, un plan bronce, uno plata, uno oro y finalmente el diamante. El personal ofrece un alojamiento de 10MB, una transferencia mensual de 100MB, una cuenta de correo electrónico y nada más. El bronce ofrece 100MB de alojamiento, 1000MB de transferencia mensual, 10 cuentas de correo electrónico. Así sucesivamente cada plan aumenta las cantidades de alojamiento, transferencia y cuentas de correo. A la cada plan agrega nuevas características. El plata ofrece acceso ssh, y una base de datos; el oro agrega estadísticas de sitio y panel de control. Así se van multiplicando las opciones, y para crear la aplicación definimos nuestro objeto que queda así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.guisho.software.patrones.builder</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.math.BigDecimal</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 *
 * @author guisho.com, luishernan@gmail.com
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PaqueteDeHosting <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">/*Los siguientes campos son obligatorios siempre*/</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nombre<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">BigDecimal</span> precioAnual<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> capacidadDeAlmacenamiento<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//en MB</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> transferenciaMensual<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//en MB</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> cantidadDireccionesCorreo<span style="color: #339933;">;</span><span style="color: #666666; font-style: italic;">//</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">/*Las siguientes son opcionales, hay planes que no los tienen*/</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> cantidadSitiosPermitidos<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> cantidadBaseDeDatos<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> codigoOferta<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> accesoSsh<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> panelDeControl<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> estadisticasDeSitio<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> ipPublica<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHosting<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">/* mas constructores */</span>
    <span style="color: #666666; font-style: italic;">/* Setters, getters y demás código....*/</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Bien, ahora cada plan tiene una configuración previamente establecida, que el vendedor no arma en el momento, y que preferiblemente no puede cambiar. ¿Cómo hacemos para crear cada objeto? La primera manera que se nos ocurrirá es crear un constructor pada cada caso, manteniendo siempre los valores obligatorios. Tendríamos una colección de constructores como la siguiente:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHosting<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nombre, <span style="color: #003399;">BigDecimal</span> precioAnual, <span style="color: #000066; font-weight: bold;">int</span> almacenamiento, <span style="color: #000066; font-weight: bold;">int</span> transferencia, <span style="color: #000066; font-weight: bold;">int</span> cantidadCorreos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombre</span> <span style="color: #339933;">=</span> nombre<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">precioAnual</span> <span style="color: #339933;">=</span> precioAnual<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">capacidadDeAlmacenamiento</span> <span style="color: #339933;">=</span> almacenamiento<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">transferenciaMensual</span> <span style="color: #339933;">=</span> transferencia<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadDireccionesCorreo</span> <span style="color: #339933;">=</span> cantidadCorreos<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHosting<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nombre, <span style="color: #003399;">BigDecimal</span> precioAnual, <span style="color: #000066; font-weight: bold;">int</span> almacenamiento, <span style="color: #000066; font-weight: bold;">int</span> transferencia, <span style="color: #000066; font-weight: bold;">int</span> cantidadCorreos, <span style="color: #000066; font-weight: bold;">int</span> basesDatos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombre</span> <span style="color: #339933;">=</span> nombre<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">precioAnual</span> <span style="color: #339933;">=</span> precioAnual<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">capacidadDeAlmacenamiento</span> <span style="color: #339933;">=</span> almacenamiento<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">transferenciaMensual</span> <span style="color: #339933;">=</span> transferencia<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadDireccionesCorreo</span> <span style="color: #339933;">=</span> cantidadCorreos<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadBaseDeDatos</span> <span style="color: #339933;">=</span> basesDatos<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHosting<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nombre, <span style="color: #003399;">BigDecimal</span> precioAnual, <span style="color: #000066; font-weight: bold;">int</span> almacenamiento, <span style="color: #000066; font-weight: bold;">int</span> transferencia, <span style="color: #000066; font-weight: bold;">int</span> cantidadCorreos, <span style="color: #003399;">String</span> ipPublica<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombre</span> <span style="color: #339933;">=</span> nombre<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">precioAnual</span> <span style="color: #339933;">=</span> precioAnual<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">capacidadDeAlmacenamiento</span> <span style="color: #339933;">=</span> almacenamiento<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">transferenciaMensual</span> <span style="color: #339933;">=</span> transferencia<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadDireccionesCorreo</span> <span style="color: #339933;">=</span> cantidadCorreos<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">ipPublica</span> <span style="color: #339933;">=</span> ipPublica<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHosting<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nombre, <span style="color: #003399;">BigDecimal</span> precioAnual, <span style="color: #000066; font-weight: bold;">int</span> almacenamiento, <span style="color: #000066; font-weight: bold;">int</span> transferencia, <span style="color: #000066; font-weight: bold;">int</span> cantidadCorreos, <span style="color: #003399;">String</span> ipPublica,<span style="color: #000066; font-weight: bold;">int</span> basesDatos<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombre</span><span style="color: #339933;">=</span>nombre<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">precioAnual</span><span style="color: #339933;">=</span>precioAnual<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">capacidadDeAlmacenamiento</span><span style="color: #339933;">=</span>almacenamiento<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">transferenciaMensual</span><span style="color: #339933;">=</span>transferencia<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadDireccionesCorreo</span><span style="color: #339933;">=</span>cantidadCorreos<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">ipPublica</span><span style="color: #339933;">=</span>ipPublica<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadBaseDeDatos</span><span style="color: #339933;">=</span>basesDatos<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
....</pre></div></div>

<p>Como vemos solo hicimos un par de combinaciones con la cantidad de bases de datos y la ip pública. Mientras la cantidad de campos opcionales crece, la cantidad de constructores aumenta desmedidamente creando el ambiente ideal para que aparezcan errores.</p>
<p>Otro camino que se puede tomar es el clásico bean: un constructor vacío y setters para cada parámetro que deseamos agregar. Este método tiene un pequeño inconveniente: podemos dejar al objeto en un estado incosistente: podemos ponerle cuántas cuentas de correo pero no ponerle nombre, ni ponerle precio. ¿Qué hacemos entonces? Hacemos un Builder!! El builder se explicará por el solo. Veamos:</p>
<p>En PaqueteDeHosting hacemos un constructor con los campos que siempre van para evitar estados inconsistentes:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHosting<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nombre, <span style="color: #003399;">BigDecimal</span> precioAnual, <span style="color: #000066; font-weight: bold;">int</span> almacenamiento, <span style="color: #000066; font-weight: bold;">int</span> transferencia, <span style="color: #000066; font-weight: bold;">int</span> cantidadCorreos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombre</span> <span style="color: #339933;">=</span> nombre<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">precioAnual</span> <span style="color: #339933;">=</span> precioAnual<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">capacidadDeAlmacenamiento</span> <span style="color: #339933;">=</span> almacenamiento<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">transferenciaMensual</span> <span style="color: #339933;">=</span> transferencia<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">cantidadDireccionesCorreo</span> <span style="color: #339933;">=</span> cantidadCorreos<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y creamos el builder</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.guisho.software.patrones.builder</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.math.BigDecimal</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 *
 * @author guisho.com, luishernan@gmail.com
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PaqueteDeHostingBuilder <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span>  PaqueteDeHosting paquete<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nombre, <span style="color: #003399;">BigDecimal</span> precio, <span style="color: #000066; font-weight: bold;">int</span> cantidadAlmacenamiento, <span style="color: #000066; font-weight: bold;">int</span> transferenciaMesual, <span style="color: #000066; font-weight: bold;">int</span> cantidadCorreo<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setNombre</span><span style="color: #009900;">&#40;</span>nombre<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setPrecioAnual</span><span style="color: #009900;">&#40;</span>precio<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setCapacidadDeAlmacenamiento</span><span style="color: #009900;">&#40;</span>cantidadAlmacenamiento<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setTransferenciaMensual</span><span style="color: #009900;">&#40;</span>transferenciaMesual<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setCantidadDireccionesCorreo</span><span style="color: #009900;">&#40;</span>cantidadCorreo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder catidadSitiosPermitidos <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> cantidad<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setCantidadSitiosPermitidos</span><span style="color: #009900;">&#40;</span>cantidad<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder cantidadBaseDeDatos <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> cantidad<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setCantidadBaseDeDatos</span><span style="color: #009900;">&#40;</span>cantidad<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder accessoSsh<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">boolean</span> acceso<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setAccesoSsh</span><span style="color: #009900;">&#40;</span>acceso<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder panelControl <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">boolean</span> panel<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setPanelDeControl</span><span style="color: #009900;">&#40;</span>panel<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder codigoOferta<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> codigo<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setCodigoOferta</span><span style="color: #009900;">&#40;</span>codigo<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> PaqueteDeHostingBuilder ipPublica <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> ip<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">paquete</span>.<span style="color: #006633;">setIpPublica</span><span style="color: #009900;">&#40;</span>ip<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Si lo analizamos el builder simplemente envuelve al objeto que creará, con una especie de métodos de acceso (parecido a un JavaBean) pero con la peculiaridad que se devuelve a sí mismo siempre. ¿En qué nos ayuda esto? Miremos el cliente como crea un Paquete ahora:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        PaqueteDeHosting personal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PaqueteDeHostingBuilder<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personal&quot;</span>,<span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BigDecimal</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span>,<span style="color: #cc66cc;">10</span>,<span style="color: #cc66cc;">100</span>,<span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        PaqueteDeHosting bronce <span style="color: #339933;">=</span>
        <span style="color: #000000; font-weight: bold;">new</span> PaqueteDeHostingBuilder<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bronce&quot;</span>,<span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BigDecimal</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">200</span><span style="color: #009900;">&#41;</span>,<span style="color: #cc66cc;">100</span>,<span style="color: #cc66cc;">1000</span>,<span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">accessoSsh</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        PaqueteDeHosting plata <span style="color: #339933;">=</span>
        <span style="color: #000000; font-weight: bold;">new</span> PaqueteDeHostingBuilder<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;plata&quot;</span>,<span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BigDecimal</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">300</span><span style="color: #009900;">&#41;</span>,<span style="color: #cc66cc;">100</span>,<span style="color: #cc66cc;">1000</span>,<span style="color: #cc66cc;">50</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">accessoSsh</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">catidadSitiosPermitidos</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">cantidadBaseDeDatos</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        PaqueteDeHosting oro <span style="color: #339933;">=</span>
        <span style="color: #000000; font-weight: bold;">new</span> PaqueteDeHostingBuilder<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;oro&quot;</span>,<span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BigDecimal</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">500</span><span style="color: #009900;">&#41;</span>,<span style="color: #cc66cc;">100</span>,<span style="color: #cc66cc;">4000</span>,<span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">accessoSsh</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">catidadSitiosPermitidos</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">cantidadBaseDeDatos</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">ipPublica</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;10.10.10.10&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como vemos esto es mucho más sencillo de leer (aparte que la línea se alarga un poco, podríamos hacer varias líneas), y deja al objeto siempre en un estado consistente. Este método de construcción por medio de llamadas encadenadas se llama interfaces fluídas, y es el punto de inicio para muchos lenguajes como Groovy, que crean construcciones bastantes complejas a partir de Builders sencillos que permiten muchas configuraciones.</p>
<p>De nuevo, este no es el Builder de GoF, que veremos en otra ocasión, pero es otro concepto de Builder. Tiene la ventaja que es fácil de entender y de implementar. Imagino que ya se les ocurrió varias maneras de implementarlo en su código actual, así que manos a la obra y a dejar bonito el código! Finalmente les dejo el <a href="http://software.guisho.com/wp-content/uploads/2009/05/builderpattern-fluidinterfaces.zip">código fuente de los ejemplos aquí.</a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://software.guisho.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a> </p>

<p>Related posts:<ol><li><a href='http://software.guisho.com/singleton-pattern-patrones-de-diseno' rel='bookmark' title='Permanent Link: Singleton Pattern &#8212; Patrones de diseño'>Singleton Pattern &#8212; Patrones de diseño</a></li>
<li><a href='http://software.guisho.com/abstract-factory-pattern-patrones' rel='bookmark' title='Permanent Link: Abstract Factory Pattern &#8211; Patrones'>Abstract Factory Pattern &#8211; Patrones</a></li>
<li><a href='http://software.guisho.com/patrones-de-diseno-factory-pattern' rel='bookmark' title='Permanent Link: Factory Pattern &#8211; Patrones'>Factory Pattern &#8211; Patrones</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Singleton Pattern &#8212; Patrones de diseño</title>
		<link>http://software.guisho.com/singleton-pattern-patrones-de-diseno</link>
		<comments>http://software.guisho.com/singleton-pattern-patrones-de-diseno#comments</comments>
		<pubDate>Thu, 14 May 2009 05:07:01 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Patrones Creacionales]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[creacionales]]></category>
		<category><![CDATA[patron singleton]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[patrones creacionales]]></category>
		<category><![CDATA[sigleton]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=101</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/singleton-pattern-patrones-de-diseno&amp;text=Singleton Pattern &#8212; Patrones de diseño&amp;via=lhernandez&amp;related=guishogt"><img align="right" src="http://software.guisho.com/wp-content/plugins//easy-twitter-button/i/buttons/es/tweetn.png" style="border: none;" alt="" /></a></div>
Estamos abordando ahora un tercer patrón creacional, o de creación. El Singleton Pattern, a diferencia de los dos que ya hemos visto y los que veremos, no se encarga de la creación de objetos en sí, sino que se enfoca en la restricción en la creación de un objeto. Este patrón es ampliamente utilizado por [...]


Related posts:<ol><li><a href='http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno' rel='bookmark' title='Permanent Link: Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño'>Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño</a></li>
<li><a href='http://software.guisho.com/patrones-de-diseno-factory-pattern' rel='bookmark' title='Permanent Link: Factory Pattern &#8211; Patrones'>Factory Pattern &#8211; Patrones</a></li>
<li><a href='http://software.guisho.com/abstract-factory-pattern-patrones' rel='bookmark' title='Permanent Link: Abstract Factory Pattern &#8211; Patrones'>Abstract Factory Pattern &#8211; Patrones</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/singleton-pattern-patrones-de-diseno&amp;text=Singleton Pattern &#8212; Patrones de diseño&amp;via=lhernandez&amp;related=guishogt"><img align="right" src="http://software.guisho.com/wp-content/plugins//easy-twitter-button/i/buttons/es/tweetn.png" style="border: none;" alt="" /></a></div>
<p><a href="http://software.guisho.com/wp-content/uploads/2009/05/singleton.jpg"><img class="alignleft size-medium wp-image-127" title="singleton" src="http://software.guisho.com/wp-content/uploads/2009/05/singleton-300x300.jpg" alt="singleton" width="300" height="300" /></a>Estamos abordando ahora un tercer patrón creacional, o de creación. El Singleton Pattern, a diferencia de los dos que ya hemos visto y los que veremos, no se encarga de la creación de objetos en sí, sino que se enfoca en la restricción en la creación de un objeto. Este patrón es ampliamente utilizado por muchos frameworks, y también es uno de los más fáciles de aprender y utilizar. </p>
<p><span id="more-101"></span>Siempre que se crea un objeto nuevo (en Java con la palabra reservada new) se invoca al constructor del objeto para que cree una instancia. Por lo general los constructores son públicos. El singleton lo que hace es convertir al constructor en privado, de manera que nadie lo pueda instanciar. Entonces, si el constructor es privado, ¿cómo se instancia el objeto? Pues a través de un método público y estático de la clase. En este método se revisa si el el objeto ha sido instanciado antes. Si no ha sido instanciado, llama al constructor y guarda el objeto creado en una variable estática del objeto. Si el objeto ya fue instanciado anteriormente, lo que hace este método es devolver la referencia al estado creado anteriormente. </p>
<p>En los patrones anteriores utilizamos un Traductor. Imaginemos que el traductor carga a memoria no sólo números, pero también diez mil palabras obtenidas a través de un archivo de texto o un web service. Cada vez que este objeto se cree utilizará mucho espacio en memoria. Además, si se usa un web services para cargarlo, cada carga consume muchos recursos de red y tarda mucho en terminarse de construir. </p>
<p>Traductor estará disponible para toda la aplicación, y en cualquier lado que se despliegue un texto será invocado. No tendría mucho sentido construir un Traductor cada vez que lo querramos utilizar. Lo más sano sería utilizar un sólo Traductor para toda la aplicación. ¿Cómo lograrlo? A través de un Singleton. Omitiendo la lógica del objeto, el código que se debería usar quedaría algo así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Traductor<span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">boolean</span> instanciated<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> Traductor traductorInstance<span style="color: #339933;">;</span>
&nbsp;
     <span style="color: #008000; font-style: italic; font-weight: bold;">/**
       *Notar que el constructor es privado!
      */</span>
      <span style="color: #000000; font-weight: bold;">private</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">//cargar un diccionario a memoria  a través de un WebService.</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Traductor getTraductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
           <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span> Traductor.<span style="color: #006633;">instanciated</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
                 Traductor.<span style="color: #006633;">traductorInstance</span><span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                 Traductor.<span style="color: #006633;">instanciated</span><span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
           <span style="color: #009900;">&#125;</span>
          <span style="color: #000000; font-weight: bold;">return</span> Traductor.<span style="color: #006633;">traductorInstance</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> translate<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> toTranslate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #666666; font-style: italic;">//mucho código bonito va aquí</span>
    <span style="color: #009900;">&#125;</span> 
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>En cualquier lugar de la aplicacion que se quiera utilizar hacer una traducción se hace esto:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Traductor.<span style="color: #006633;">getTraductor</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">translate</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unaPalabra&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>¿Qué logramos con esto? Que alguien que utilice nuestro código no pueda hacer esto</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Traductor t <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Es un gran beneficio porque podemos controlar mejor, cambiarla en el futuro, optimizarla, a Traductor. Evita malos usos de la clase y se nos asegura que a lo más hay una instancia del objeto en toda la aplicación.</p>
<p>Las cosas no son tan fáciles como parecen. Hay muchas maneras de crear los Singletons. En este ejemplo utilizamos un booleano estático, pero no siempre es necesario, pudimos haber inicializado traductorInstance como null, y en vez de verificar la variable booleana, verificar si la instancia es null o no.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Traductor<span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span>  Traductor traductorInstance<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
      <span style="color: #008000; font-style: italic; font-weight: bold;">/**
       *Notar que el constructor es privado!
      */</span>
      <span style="color: #000000; font-weight: bold;">private</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">//cargar un diccionario a memoria  a través de un WebService.</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Traductor getTraductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
           <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span> Traductor.<span style="color: #006633;">INSTANCE</span><span style="color: #339933;">==</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
                 Traductor.<span style="color: #006633;">traductorInstance</span><span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
           <span style="color: #009900;">&#125;</span>
          <span style="color: #000000; font-weight: bold;">return</span> Traductor.<span style="color: #006633;">traductorInstance</span><span style="color: #339933;">;</span>
   	<span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> translate<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> toTranslate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #666666; font-style: italic;">//mucho código bonito va aquí</span>
    <span style="color: #009900;">&#125;</span> 
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O, para hacer las cosas más fáciles (que no siempre conviene, jeje) podríamos evitar la evaluación en getTraductor y crear el objeto cuando lo declaramos:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Traductor<span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span>  Traductor traductorInstance<span style="color: #339933;">=</span><span style="color: #000000; font-weight: bold;">new</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #008000; font-style: italic; font-weight: bold;">/**
       *Notar que el constructor es privado!
      */</span>
      <span style="color: #000000; font-weight: bold;">private</span> Traductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">//cargar un diccionario a memoria  a través de un WebService.</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Traductor getTraductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
           <span style="color: #000000; font-weight: bold;">return</span> Traductor.<span style="color: #006633;">traductorInstance</span><span style="color: #339933;">;</span>
   	<span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> translate<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> toTranslate<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #666666; font-style: italic;">//mucho código bonito va aquí</span>
    <span style="color: #009900;">&#125;</span> 
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Fácil ¿no? Mmm, pues se puede complicar. En Java por ejemplo, todavía se podría obtener una copia de traductor así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Traductor t <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Traductor<span style="color: #009900;">&#41;</span>Traductor.<span style="color: #006633;">getTraductor</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Para evitar esto tendríamos que añadir las siguietnes líneas a nuestra clase Traductor</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> clone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">CloneNotSupportedException</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">CloneNotSupportedException</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span></pre></div></div>

<p>También alguien podría extender la clase y volver público el constructor. Para evitar esto sería buena idea declarar nuestra clase como final.</p>
<p>Hay que tener <strong>especial cuidado </strong> cuando el Singleton se utiliza en un ambiete multi hilos, porque puede crear problemas si no se implementa de la manera adecuada. En Java es posible que tengamos que meter algún synchronized por ahí para evitar problemas.</p>
<p>Concluyendo, la  idea central del Singleton es esa: asegurar de que exista tan solo una instancia del objeto en toda la aplicación. Hay muchas maneras de implementar un Singleton (aquí solo vimos algunas). Es un patrón muy aplicado en Java, aunque, como todos los patrones, se puede implementar en cualquier lenguaje orientado a objetos.  También se pueden hacer cosas interesantes uniendo el Singleton con otros patrones creacionales (recordemos que el singleton no busca crear, sino que limitar la creación).</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://software.guisho.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a> </p>

<p>Related posts:<ol><li><a href='http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno' rel='bookmark' title='Permanent Link: Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño'>Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño</a></li>
<li><a href='http://software.guisho.com/patrones-de-diseno-factory-pattern' rel='bookmark' title='Permanent Link: Factory Pattern &#8211; Patrones'>Factory Pattern &#8211; Patrones</a></li>
<li><a href='http://software.guisho.com/abstract-factory-pattern-patrones' rel='bookmark' title='Permanent Link: Abstract Factory Pattern &#8211; Patrones'>Abstract Factory Pattern &#8211; Patrones</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://software.guisho.com/singleton-pattern-patrones-de-diseno/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Factory Pattern &#8211; Patrones</title>
		<link>http://software.guisho.com/patrones-de-diseno-factory-pattern</link>
		<comments>http://software.guisho.com/patrones-de-diseno-factory-pattern#comments</comments>
		<pubDate>Tue, 28 Apr 2009 22:57:49 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[Patrones Creacionales]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[factory pattern]]></category>
		<category><![CDATA[patrón de fábrica]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[patrones creacionales]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=55</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/patrones-de-diseno-factory-pattern&amp;text=Factory Pattern &#8211; Patrones&amp;via=lhernandez&amp;related=guishogt"><img align="right" src="http://software.guisho.com/wp-content/plugins//easy-twitter-button/i/buttons/es/tweetn.png" style="border: none;" alt="" /></a></div>
Los patrones creacionales (creational patterns) son aquellos que tienen que ver con la creación (duh!) de objetos. La razón de ser de estos patrones es para facilitar, ordenar, o ayudar en la creación de objetos. Dependiendo del lenguage de programación que estemos utilizando, generalmente crearemos un objeto así: Objeto o = new Objeto(). Pues bueno, [...]


Related posts:<ol><li><a href='http://software.guisho.com/abstract-factory-pattern-patrones' rel='bookmark' title='Permanent Link: Abstract Factory Pattern &#8211; Patrones'>Abstract Factory Pattern &#8211; Patrones</a></li>
<li><a href='http://software.guisho.com/singleton-pattern-patrones-de-diseno' rel='bookmark' title='Permanent Link: Singleton Pattern &#8212; Patrones de diseño'>Singleton Pattern &#8212; Patrones de diseño</a></li>
<li><a href='http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno' rel='bookmark' title='Permanent Link: Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño'>Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/patrones-de-diseno-factory-pattern&amp;text=Factory Pattern &#8211; Patrones&amp;via=lhernandez&amp;related=guishogt"><img align="right" src="http://software.guisho.com/wp-content/plugins//easy-twitter-button/i/buttons/es/tweetn.png" style="border: none;" alt="" /></a></div>
<p>Los patrones creacionales (creational patterns) son aquellos que tienen que ver con la creación (duh!) de objetos. La razón de ser de estos patrones es para facilitar, ordenar, o ayudar en la creación de objetos. Dependiendo del lenguage de programación que estemos utilizando, generalmente crearemos un objeto así: Objeto o = new Objeto(). Pues bueno, en los patrones creacionales las cosas cambian un poquito, y probablemente ahora crearemos un objeto así Objeto o = ObjectoFactory.getInstance(&#8220;x&#8221;);, o algo parecido.</p>
<p> </p>
<p>Hoy hablaremos del más famoso de los patrones de creación: en Factory Pattern (Patrón de fábrica). Utilizaremos los nombres ingleses porque creo que son más claros que las traducciones que se podrían hacer. Además, en software de todos lados, es más estandar utilizar el inglés en ciertas nomenclaturas para facilitar que otros lean nuestro código. Buhh, alguien alega por ahí, pero reconzcámoslo: programamos en inglés. </p>
<p><span id="more-55"></span></p>
<p> </p>
<p>Como todo se entiende mejor con un ejemplo -al menos eso creo yo-, comenzaremos con uno. Supongamos se nos encarga crear un traductor que devuelva los números del cero al diez en tres idiomas: inglés, español, y alemán. Existen muchísimas maneras de hacer esto. Al final, se desea un método que reciba un entero entre 0 y 10 y que devuelva una cadena con el nombre de dicho número en el idioma que se esté trabajando. </p>
<p> </p>
<p>Una manera de entrarle al problema podría ser algo así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MainClient <span style="color: #009900;">&#123;</span>
<span style="color: #000000; font-weight: bold;">public</span> MainClient<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> traducirNumero<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> idioma, <span style="color: #000066; font-weight: bold;">int</span> numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;español&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		  <span style="color: #000000; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span>numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		     <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;uno&quot;</span><span style="color: #339933;">;</span>
		     <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;dos&quot;</span><span style="color: #339933;">;</span>
		    ....
		   <span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;english&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		    <span style="color: #000000; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span>numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		     <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;one&quot;</span><span style="color: #339933;">;</span>
		     <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;two&quot;</span><span style="color: #339933;">;</span>
		    ....
		    <span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span> 
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;deutsch&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		    <span style="color: #000000; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span>numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		     <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;eins&quot;</span><span style="color: #339933;">;</span>
		     <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;zwei&quot;</span><span style="color: #339933;">;</span>
		    ....
		    <span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//traducirNumero</span>
       
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
MainClient mc <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MainClient<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>mc.<span style="color: #006633;">traducirNumero</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;espanol&quot;</span>,<span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//de la clase</span></pre></div></div>

<p> El resultado del código anterior, como ya sabrán, es <strong>uno.</strong></p>
<p>Esta solución parece funcionar, y de hecho lo hace. Pero imaginemos que ahora nos dicen que desean la traducción de todos los números? Sin duda el código comenzará a crecer. Y claro, ahora tendremos que agregar código de lógica para cada idioma para escribir números como 752, 1233, etc. </p>
<p>Como nos gusta hacer gala de nuestro enfoque a objetos, los primero que se nos ocurre es una herencia. Definiremos una clase abstracta Traductor, y para cada idioma haremos una subclase de Traductor.</p>
<p> </p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> Traductor<span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #003399;">String</span> traducirNumero<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y ahora comienza la magia a aparecer. Vamos a crear una clase especializada para diccionario, que se encargará de traducir los números. Tendremos una clase especializada para traducir los números al español, que iría algo así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TraductorEspanol <span style="color: #000000; font-weight: bold;">extends</span> Traductor <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> TraductorEspanol<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       ...
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> traducirNumero<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">switch</span><span style="color: #009900;">&#40;</span>numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       	   <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;uno&quot;</span><span style="color: #339933;">;</span>
       	   <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;dos&quot;</span><span style="color: #339933;">;</span>
       	   ...
       <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>	
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>La clase para el inglés iría</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TraductorIngles <span style="color: #000000; font-weight: bold;">extends</span> Traductor <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> TraductorIngles<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       ...
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> traducirNumero<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">switch</span><span style="color: #009900;">&#40;</span>numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
       	   <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;one&quot;</span><span style="color: #339933;">;</span>
       	   <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;two&quot;</span><span style="color: #339933;">;</span>
       	   ...
       <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>	
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y la del alemán no la ponemos, porque ya captaron la idea. Ahora, en el momento de querer utilizar un diccionario, se llamaría algo así</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Traductor t <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorEspanol<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
t.<span style="color: #006633;">traducirNumero</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Entonces, la clase MainClient cambiaría un poco y quedaría así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MainClient <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span>  traducirNumero<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		Traductor traductor <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;español&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			traductor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorEspanol<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ingles&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			traductor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorIngles<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> 
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;aleman&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			traductor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorAleman<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #003399;">String</span> toReturn traductor.<span style="color: #006633;">traducirNumero</span><span style="color: #009900;">&#40;</span>numero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">return</span> toReturn<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//traducirNumero</span>
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          MainClient mc <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MainClient<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>mc.<span style="color: #006633;">traducirNumero</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;espanol&quot;</span>,<span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//de la clase</span></pre></div></div>

<p>Qué hemos ganado? Primero, nuestro código es mucho más legible. Segundo es bastante más escalable. Podemos agregar el traductor para el francés muy fácilmente. Tercero hemos escondido la manera en la que traducimos a Tradúceme. Por ejemplo, puede ser que las traducciones a chino las vayamos a traer a un web Service. En ese caso TraductorChino se encargaría de hacer todo el ajetreo de conectarse a internet y buscar el web services, pero los demás ni se enteran.</p>
<p>Pero el Factory Pattern no ha aperecido, Es tiempo de irlo a llamar. Bueno, Traduceme está haciendo algo que no le compete: está eligiendo la instancia de Traductor que quiere usar. Imaginen que se usa el traductor en 100 lugares,  entonces en cien lugares se tiene que buscar qué clase de Traductor vamos a instanciar. El patrón de fábrica -factory pattern- nos esconde esa lógica. Vamos a agregar ahora nuestra fábrica de traductores.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TraductorFactory <span style="color: #009900;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">public</span> TraductorFactory<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
     <span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Traductor createTraductor<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		Traductor traductor <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma<span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;español&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			traductor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorEspanol<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma<span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;english&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			traductor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorIngles<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> 
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>idioma<span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;deutsch&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			traductor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TraductorAleman<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> traductor<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//de la clase</span></pre></div></div>

<p>¿Qué hace TraductorFactory? Simplemente elige, en base a los argumentos dados &#8211; en este caso el idioma- qué clase de traductor se instanciará. Traduceme de nuevo cambia y quedaría así:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MainClient <span style="color: #009900;">&#123;</span>
     <span style="color: #003399;">String</span> idioma<span style="color: #339933;">;</span>
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span>Strin <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>args<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		Traductor traductor <span style="color: #339933;">=</span> TraductorFactory.<span style="color: #006633;">createTraductor</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;espanol&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span> traductor.<span style="color: #006633;">traducirNumero</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//main</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//de la clase</span></pre></div></div>

<p>MainClient se ha visto dramáticamente reducido, y su código es muy fácil de leer. Quien quiera usar un traductor simplemente hará llamar a Traduceme. Traduceme sabe el idioma que eligieron, pero no sabe que subclase de Traductor instanciar, pero sabiendo el idioma TraductorFactory sabe exáctamente qué instancia de Traductor crear. Si la aplicación desea cambiar de idioma simplemente le envía otro parámetro a Traduceme y listo. También agregar idiomas es más manejable que antes. </p>
<p>El Factory Pattern esconde al usuario final dle código la desición de qué sublclase instanciar, y promueve el encapsulamiento de las partes más variables del sistema. En términos generales, una fábrica abstracta consiste de las siguientes partes:</p>
<ul>
<li>Un cliente, que es el que llama a la fábrica (en nuestro caso MainClient).</li>
<li>Una fábrica, que decidé la clase a instanciar (TraductorFactory).</li>
<li>Un prodicto, lo que la fábrica devuelve (para nosotros las instancias de Traductor).</li>
</ul>
<p> </p>
<p>Pueden bajar los fuentes de este <a href="http://software.guisho.com/wp-content/uploads/2009/04/factorypattern.zip">ejemplo aqui</a>.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://software.guisho.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a> </p>

<p>Related posts:<ol><li><a href='http://software.guisho.com/abstract-factory-pattern-patrones' rel='bookmark' title='Permanent Link: Abstract Factory Pattern &#8211; Patrones'>Abstract Factory Pattern &#8211; Patrones</a></li>
<li><a href='http://software.guisho.com/singleton-pattern-patrones-de-diseno' rel='bookmark' title='Permanent Link: Singleton Pattern &#8212; Patrones de diseño'>Singleton Pattern &#8212; Patrones de diseño</a></li>
<li><a href='http://software.guisho.com/builder-pattern-interfaces-fluidas-patrones-de-diseno' rel='bookmark' title='Permanent Link: Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño'>Builder Pattern, Interfaces Fluidas&#8211; Patrones de diseño</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://software.guisho.com/patrones-de-diseno-factory-pattern/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

