



<?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 de diseño</title>
	<atom:link href="http://software.guisho.com/temas/patrones-de-diseno/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>Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño</title>
		<link>http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno</link>
		<comments>http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno#comments</comments>
		<pubDate>Thu, 19 Nov 2009 21:41:37 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[Ingeniería de software]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[Patrones Estructurales]]></category>
		<category><![CDATA[adaptador]]></category>
		<category><![CDATA[adapter pattern]]></category>
		<category><![CDATA[patron adaptador]]></category>
		<category><![CDATA[patron adapter]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[wrapper]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=179</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno&amp;text=Patron Adaptador &#8211; Pattern Adapter &#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 patrón estructural que ahora vamos a analizar es muy eficaz así como sencillo. Se puede utilizar en muchos contextos y es de especialidad utilidad cuando se utilizan códigos o librerías ajenos al que estamos utilizando y sobre el que no tenemos control. Este patrón se le conoce como adaptador o adapter en inglés, aunque [...]


Related posts:<ol><li><a href='http://software.guisho.com/prototype-pattern-patron-prototipo-patrones-de-diseno' rel='bookmark' title='Permanent Link: Prototype Pattern &#8211; Patron Prototipo &#8212; Patrones de diseño'>Prototype Pattern &#8211; Patron Prototipo &#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>
<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/patron-adaptador-pattern-adapter-patrones-de-diseno&amp;text=Patron Adaptador &#8211; Pattern Adapter &#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><a href="http://software.guisho.com/wp-content/uploads/2009/11/adaptador.jpg"><img class="alignleft size-full wp-image-181" title="adaptador" src="http://software.guisho.com/wp-content/uploads/2009/11/adaptador.jpg" alt="adaptador" width="240" height="240" /></a>El patrón estructural que ahora vamos a analizar es muy eficaz así como sencillo. Se puede utilizar en muchos contextos y es de especialidad utilidad cuando se utilizan códigos o librerías ajenos al que estamos utilizando y sobre el que no tenemos control. Este patrón se le conoce como adaptador o adapter en inglés, aunque algunos lo llaman también wrapper, que viene siendo como envoltorio. Ambos nombres tienen bastante sentido y explican el por qué de este patrón.</p>
<p><span id="more-179"></span></p>
<p>Antes de comenzar con código o parecido, pensemos en este problema. En muchos países se utilizan las espigas redondas en los tomacorrientes, y en otros las espigas planitas. En ocasiones tenemos un dispositivo que tiene 3 espigas y el tomacorrientes 2. Sin embargo sabemos que el aparato que deseamos conectar &#8220;entiende&#8221; la corriente eléctrica, &#8220;la acepta&#8221;, aunque la interfaz para conectarse a ella sea una distinta a la que posee. ¿Qué hacemos en estos casos? Usamos un adaptador! O un convertidor, o un transformador, cómo le querramos llamar.  Pues lo mismo sucede con el software. Sucede a menudo que nos encontramos con librerías que pueden sernos de utilidad, pero que existe la necesidad de adaptarnos a ellas. En esos casos tenemos dos opciones: modificar todo nuestro código para que se adapte a la librería, o podemos crear un adaptadro que traduzca lo nuestro a lo de ellos y lo de ellos a lo nuestro. Un ejemplo sencillo en el mundo Java es el de los Enumeration y los Iterators. Ambos tienen un hasNext()  o  un hasMoreElements() que hacen lo mismo; al igual que un next() y un nextElement() que hacen lo mismo. Imaginemos todo lo queremos manejar con Iterators, podemos crear un adaptador que nos &#8220;convierta&#8221; entre Iterator y Enumeration.</p>
<p>Vamos con el usual ejemplo. Imaginemos tenemos un sistema que maneja coches, barcos, aviones y parecidos. Generalmente los motores que se usan son de gasolina, pero las nuevas tendencias han popularizado los motores eléctricos. Para simplificar mi caso y mostra bien el punto, tenemos que el proveedor de vehículos eléctricos nos provee sus librerías para el motor eléctrico que es prácticamente igual a nuestras implementaciones pero con otros nombres (prender en vez de encender, &#8220;mover más rápido&#8221; en vez de acelerar, etc.), y tiene una restricción extra: para poder acelerar o detener el motor, este tiene que estar conectado. Y surge el problema ¿cómo hacemos para nuestras librerías puedan hacer uso del motor eléctrico? Podríamos reescribirlas todas, pero el tiempo que eso nos tomaría sería mucho. Además sabemos que existirían problemas que nuestras librerías ya han solucionado.</p>
<p>Como nos gusta ser elegantes en nuestro uso de objetos, hace muchos años creamos una clase abstracta (pensamos también hacer una interfaz, pero la clase abstracta nos provee otros métodos útiles):</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.adapter</span><span style="color: #339933;">;</span>
<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> Motor <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> encender<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> acelerar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apagar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #666666; font-style: italic;">//...mas metodos que hacen muchas cosas</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y tenemos nuestras implementaciones de algunos motores, por ejemplo el motor económico:</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.adapter</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MotorEconomico <span style="color: #000000; font-weight: bold;">extends</span> Motor <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> MotorEconomico<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: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Craendo motor economico&quot;</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: #000066; font-weight: bold;">void</span> encender<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Encendiendo motor economico.&quot;</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: #000066; font-weight: bold;">void</span> acelerar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Acelerando motor economico.&quot;</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: #000066; font-weight: bold;">void</span> apagar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Apagando motor economico.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y el motor gastón (que ya no se vende tanto!):</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.adapter</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MotorGaston <span style="color: #000000; font-weight: bold;">extends</span> Motor <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> MotorGaston<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: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Creando el motor gaston&quot;</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: #000066; font-weight: bold;">void</span> encender<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Bum, bum....encendiendo motor gaston&quot;</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: #000066; font-weight: bold;">void</span> acelerar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Buuuuuuuuuuuum, acelerando y gastando muuuucha gas&quot;</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: #000066; font-weight: bold;">void</span> apagar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Apagando motor gaston&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Estas clases siempre nos han funcionado bien, y de hecho tienen muchas cosas como servicios, mantenimientos y otros, que usamos gracias a la interfaz motor. Por ejemplo es común que usemos cosas como estás:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">        Motor motor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MotorEconomico<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">encender</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">acelerar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">apagar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #666666; font-style: italic;">//hacer mas cosas....</span>
        motor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MotorGaston<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">encender</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">acelerar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">apagar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Ahora la empresa que construye motores eléctricos nos manda su propia implementación que va 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> MotorElectrico <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> conectado <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> MotorElectrico<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Creando motor electrico&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conectado</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</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: #000066; font-weight: bold;">void</span> conectar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Conectando motor eléctrico&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conectado</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>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> activar<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><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conectado</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;No se puede activar porque no esta conectado el motor electrico&quot;</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;">else</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Esta conectado, activando motor electrico....&quot;</span><span style="color: #009900;">&#41;</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;">public</span> <span style="color: #000066; font-weight: bold;">void</span> moverMasRapido<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><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conectado</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;No se puede mover rapido el motor electrico porque no esta conectado...&quot;</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;">else</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Moviendo mas rapido...aumentando voltaje&quot;</span><span style="color: #009900;">&#41;</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;">public</span> <span style="color: #000066; font-weight: bold;">void</span> detener<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><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conectado</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;No se puede detener motor electrico porque no esta conectado&quot;</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;">else</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Deteniendo motor electrico&quot;</span><span style="color: #009900;">&#41;</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;">public</span> <span style="color: #000066; font-weight: bold;">void</span> desconectar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Desconectando motor electrico...&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conectado</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como vemos, este motor hace lo mismo que el nuestro, pero de manera y con llamadas un poco diferentes. ¿Cómo hacemos para integrar este MotorEléctrico al resto de nuestro sistema? Así es, con un adaptador o adapter!<br />
El adapter &#8220;envuelve&#8221; al objeto extraño (por eso le llaman wrapper también, ya que wrapper viene siendo envoltorio).</p>
<p>Nuestro adaptador se escribiría 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.adapter</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MotorElectricoAdapter <span style="color: #000000; font-weight: bold;">extends</span> Motor<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> MotorElectrico motorElectrico<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> MotorElectricoAdapter<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: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">motorElectrico</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MotorElectrico<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><span style="color: #0000ff;">&quot;Creando motor Electrico adapter&quot;</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: #000066; font-weight: bold;">void</span> encender<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Encendiendo motorElectricoAdapter&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">motorElectrico</span>.<span style="color: #006633;">conectar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">motorElectrico</span>.<span style="color: #006633;">activar</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: #000066; font-weight: bold;">void</span> acelerar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Acelerando motor electrico...&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">motorElectrico</span>.<span style="color: #006633;">moverMasRapido</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: #000066; font-weight: bold;">void</span> apagar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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><span style="color: #0000ff;">&quot;Apagando motor electrico&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">motorElectrico</span>.<span style="color: #006633;">detener</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">motorElectrico</span>.<span style="color: #006633;">desconectar</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>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como ven el adapter se encarga no solo de corregir los nombres de los métodos, sino también cosas como conectar y desconectar el motor, cosas que a nuestra implementación no le importan. Pero lo más importante es que ahora podemos utilizar esta implemetnación de Motor en nuestro sistema utilizando la implementación de ellos. Por ejemplo podemos hacer cosas como esta:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">        Motor motor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MotorEconomico<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">encender</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">acelerar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">apagar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        motor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MotorGaston<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">encender</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">acelerar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">apagar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        motor <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MotorElectricoAdapter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">encender</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">acelerar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        motor.<span style="color: #006633;">apagar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>El patrón adapter aparece en todos lados, aunque muchas veces no se le llama adapter específicamente. Ahora que lo conocemos lo podemos usar en nuevos proyectos, o tal vez puede solucionarlos problemas que resolvimos a medias en algún software por ahí. Como siempre les <a href="http://software.guisho.com/wp-content/uploads/2009/11/adapter.zip">dejo el código fuente.</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/prototype-pattern-patron-prototipo-patrones-de-diseno' rel='bookmark' title='Permanent Link: Prototype Pattern &#8211; Patron Prototipo &#8212; Patrones de diseño'>Prototype Pattern &#8211; Patron Prototipo &#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>
<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/patron-adaptador-pattern-adapter-patrones-de-diseno/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Patrones estructurales (structural patterns)</title>
		<link>http://software.guisho.com/patrones-estructurales-structural-patterns</link>
		<comments>http://software.guisho.com/patrones-estructurales-structural-patterns#comments</comments>
		<pubDate>Fri, 19 Jun 2009 17:06:57 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[Patrones Estructurales]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[patrones estructurales]]></category>
		<category><![CDATA[structural patterns]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=165</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/patrones-estructurales-structural-patterns&amp;text=Patrones estructurales (structural patterns)&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>
Vimos ya los patrones creacionales más importantes. No son todos, en el futuro veremos más, pero son los más usados y los más importantes. Ahora comenzamos con una nueva fase: Los patrones estructurales. Los patrones estructurales (structural patterns) podrían llamarse patrones de relaciones, o algo parecido, porque su principal función es facilitar y mejorar las [...]


Related posts:<ol><li><a href='http://software.guisho.com/patrones-de-diseno' rel='bookmark' title='Permanent Link: Patrones de Diseño'>Patrones de Diseño</a></li>
<li><a href='http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno' rel='bookmark' title='Permanent Link: Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño'>Patron Adaptador &#8211; Pattern Adapter &#8211; 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-estructurales-structural-patterns&amp;text=Patrones estructurales (structural patterns)&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/06/spider.jpg"><img class="alignleft size-medium wp-image-166" title="spider" src="http://software.guisho.com/wp-content/uploads/2009/06/spider-300x270.jpg" alt="spider" width="300" height="270" /></a>Vimos ya los patrones creacionales más importantes. No son todos, en el futuro veremos más, pero son los más usados y los más importantes. Ahora comenzamos con una nueva fase: Los patrones estructurales. Los patrones estructurales (structural patterns) podrían llamarse patrones de relaciones, o algo parecido, porque su principal función es facilitar y mejorar las relaciones entre objetos.</p>
<p><span> </span>En el mundo de objetos, la creación de instancias es muy importante, pero tan importante como la creación, es la manera en la que instancias de objetos se comunican entre sí. Un diseño estandarizado y bien pensado puede facilitar mucho las cosas durante el desarrollo de un sistema grande. En ocasiones nos ponemos a realizar nuestras soluciones a la medida, pero generalmente estas solucionen decaen en construcciones extrañas que serán difíciles de entender para futuros desarrolladores, e incluso para nosotros mismos una vez que dejemos de ver el código.</p>
<p><span id="more-165"></span></p>
<p><span> </span>Una solución elegante es utilizar inteligentemente patrones estructurales. Pero cuidado, puede ser arma de dos filos. Podemos caer en la tentación de meter patrones en todos lados, incluso cuando no es necesario. Nuestro código puede comenzar a crecer y crecer sin hacer aún nada, bajo la premisa de que todo lo queremos hacer con patrones.</p>
<p><span> </span>Los patrones son una herramienta de diseño muy poderosa, pero hay que saberla utilizar. El tiempo y la experiencia suelen ser los mejores acompañantes para un diseñador de software, porque sólo el tiempo le dará el colmillo para utilizar sus herramientas adecuadamente.</p>
<p><span> </span>Con mucha frecuencia el diseño de un dominio inicia con nociones sumamente intuitivas. Conforme el diseño se va destilando y mejorando, se agregan soluciones específicas de software (como patrones), que lo pueden ir complicando (con el propósito de hacerlo más manejable). Generalmente los patrones estructurales entran en la jugada en etapas medias del diseño, y muchísimas veces son el resultado de refactorización (refactoring).</p>
<p><span> </span>Así que comenzamos con los patrones estructurales. Encendamos motores y preparemos la mente, porque estos patrones son buenos martillos y desatornilladores que podemos meter en nuestra caja de herramientas. Sin dudas algún día nos serán de mucha utilidad en medio de un proyecto, y la gente quedará sorprendida de como resuelves elegantemente los problemas <img src='http://software.guisho.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p><a href="http://www.flickr.com/photos/43145783@N00/2124673642/">Foto por.</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/patrones-de-diseno' rel='bookmark' title='Permanent Link: Patrones de Diseño'>Patrones de Diseño</a></li>
<li><a href='http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno' rel='bookmark' title='Permanent Link: Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño'>Patron Adaptador &#8211; Pattern Adapter &#8211; 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-estructurales-structural-patterns/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Prototype Pattern &#8211; Patron Prototipo &#8212; Patrones de diseño</title>
		<link>http://software.guisho.com/prototype-pattern-patron-prototipo-patrones-de-diseno</link>
		<comments>http://software.guisho.com/prototype-pattern-patron-prototipo-patrones-de-diseno#comments</comments>
		<pubDate>Tue, 02 Jun 2009 18:40:00 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Patrones Creacionales]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[patron prototipo]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[prototipo]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[prototype pattern]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=142</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/prototype-pattern-patron-prototipo-patrones-de-diseno&amp;text=Prototype Pattern &#8211; Patron Prototipo &#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>
Ya casi terminando con los patrones creacionales, vamos a hablar hoy sobre el prototype pattern, o patrón prototipo. Como los demás patrones creacionales, este patrón sustituirá para el cliente la palabra clave new por otra forma de crear objetos. En este caso específico la creación se hará sobre objetos que son complicados de crear, que [...]


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/patron-adaptador-pattern-adapter-patrones-de-diseno' rel='bookmark' title='Permanent Link: Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño'>Patron Adaptador &#8211; Pattern Adapter &#8211; 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/prototype-pattern-patron-prototipo-patrones-de-diseno&amp;text=Prototype Pattern &#8211; Patron Prototipo &#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/06/cloning.jpg"><img class="alignleft size-medium wp-image-143" title="cloning" src="http://software.guisho.com/wp-content/uploads/2009/06/cloning-300x224.jpg" alt="cloning" width="300" height="224" /></a>Ya casi terminando con los patrones creacionales, vamos a hablar hoy sobre el prototype pattern, o patrón prototipo. Como los demás patrones creacionales, este patrón sustituirá para el cliente la palabra clave new por otra forma de crear objetos. En este caso específico la creación se hará sobre objetos que son complicados de crear, que para evitar usar new  serán clonados a partir de una instancia ya existente. Afortunadamente crear objetos no crea ningún tipo de reparo moral, porque este patrón de eso se trata: de clonar, de pasar el ADN de un objeto a otro.  Es decir cada instancia del objeto se obtendrá a partir de un prototipo (sí, de ahí el nombre del patrón!). </p>
<p><span id="more-142"></span></p>
<p>Este patrón es facilito, ya lo veremos. En el caso específico de Java ya se tiene mucho camino ganado, porque Java provee la interaz clonable con el propósito de crear clones en mente. Pero vamos a hacer también una implementación sin usar esta interfaz para comprender completamente la idea detrás del prototipo. La primera manera de implementar este patrón en Java es implementando la interfaz Cloneable. Mas abajo veremos otra forma de implementarlo, que es haciéndolo a mano, con una ventaja extra: en vez de crear referencias a los objetos contenidos, podemos crear objetos nuevos, que en muchos cosas nos puede ser de utilidad. Por ahora veamos un un ejemplo sencillo usando cloneable:</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> Copiame <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Cloneable</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">Object</span> clone <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;">try</span> <span style="color: #009900;">&#123;</span>
				clone <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">clone</span><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;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">CloneNotSupportedException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				e.<span style="color: #006633;">printStackTrace</span><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> clone<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Expliquemos un poco. Clonable es una interfaz vacía, pero para utilizar super.clone() tenemos que implementar cloneable si no quere mos una CloneNoSupportedException. La segunda cosa a considerar es que clone hace una copia de los valores de los campos de un objeto, no de los objetos a los que apunta. En otras palabras, el objeto clonado  apuntará a los mismos objetos que el objeto antiguo apuntaba. Otra cosa a tomar en cuenta es que clone() devuelve siempre un Object. También notemos que clone es un método protected que puede ser llamado solo por la misma clase o el paquete que la contiene.</p>
<p> </p>
<p> </p>
<p>Entonces, ¿para qué nos sirve clonar objetos? Bueno, nos sirve para copiar objetos que tardan mucho en crear, o que son complejos de crear. Por ejemplo una lista grande que es costoso  en tiempo obtener y que se desea ordenar de dos maneras distintas.</p>
<p> </p>
<p> </p>
<p>De nuevo nos adentraremos con un ejemplo, que sigo pensando es la mejor manera de aprender. Para nuestro ejemplo vamos a hacer una clase Persona y luego llenar la persona con los datos de dos hermanos: Juan y María que serán ingresados a un sistema x.</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.prototype</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> Persona <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Cloneable</span><span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> nombres<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> appellidos<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> nombrePadre<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> nombreMadre<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> direccion<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> telCasa<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> nacionalidad<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> ciudadEnQueVive<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> nombreMascota<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Persona<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;">/*Setters y geters....*/</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y un cliente que crea la Persona:</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>
        Persona juan <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Persona<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setNombres</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Juan José&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setAppellidos</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pérez Ramirez&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setNombrePadre</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Juan Pérez Martinez&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setNombreMadre</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;María Ramirez&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setDireccion</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;9a. Ave. 43-12 Z.1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setTelCasa</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;34567890&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setNacionalidad</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Guatemalteca&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setCiudadEnQueVive</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Guatemala&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        juan.<span style="color: #006633;">setNombreMascota</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pepito&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">//Hacer algo con Juan, ingresarlo al sistema, etc...</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><span style="color: #0000ff;">&quot;Ingresando al sistema :&quot;</span><span style="color: #339933;">+</span>juan.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Persona maria <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Persona<span style="color: #009900;">&#41;</span>juan.<span style="color: #006633;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        maria.<span style="color: #006633;">setNombres</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;María Inés&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><span style="color: #0000ff;">&quot;Ingresando al sistema :&quot;</span><span style="color: #339933;">+</span>maria.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">//ingresar a Maria al sistema....</span>
&nbsp;
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como vemos, ahora no se tuvieron que ingresar todos los campos de María sino, solo aquellos que la diferenciaban de su hermano Juan. Hay que recordar que si hubiesen objetos en el ejemplo estos se clonan por referencia, es decir las referencias de ambos objetos son las mismas.  Ahora vamos a vamos a implementar la clonación a mano. Le vamos a añadir a Persona este método:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> Persona creaPrototipo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        Persona p <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Persona<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setNombres</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombres</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setAppellidos</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">appellidos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setNombrePadre</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombrePadre</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setNombreMadre</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombreMadre</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setDireccion</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">direccion</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setTelCasa</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">telCasa</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setNacionalidad</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nacionalidad</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setCiudadEnQueVive</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">ciudadEnQueVive</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        p.<span style="color: #006633;">setNombreMascota</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nombreMascota</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><span style="color: #0000ff;">&quot;Creado prototipo de Persona&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> p<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Entonces en el cliente podemos hacer esta llamada</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">        Persona maria <span style="color: #339933;">=</span> juan.<span style="color: #006633;">creaPrototipo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Como vemos, el patrón prototipo es sencillo: crear una copia de un objeto para ahorrarnos los pasos de su creación, o para optimizar accesos o procesos que ya se hicieron en un objeto similar y crear una copia del objeto ya con esos datos ingresados. Como siempre les dejo aquí el <a href="http://software.guisho.com/wp-content/uploads/2009/06/patronprototipo.zip">código para que jueguen.</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/patron-adaptador-pattern-adapter-patrones-de-diseno' rel='bookmark' title='Permanent Link: Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño'>Patron Adaptador &#8211; Pattern Adapter &#8211; 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/prototype-pattern-patron-prototipo-patrones-de-diseno/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<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>Abstract Factory Pattern &#8211; Patrones</title>
		<link>http://software.guisho.com/abstract-factory-pattern-patrones</link>
		<comments>http://software.guisho.com/abstract-factory-pattern-patrones#comments</comments>
		<pubDate>Wed, 06 May 2009 03:53:26 +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[abstract factory pattern]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=86</guid>
		<description><![CDATA[
<div style="float: right; padding-left: 5px;" class="twitterbutton"><a href="http://twitter.com/share?url=http://software.guisho.com/abstract-factory-pattern-patrones&amp;text=Abstract 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>
Hace una semana hablamos del Factory Pattern, que realmente se llama Factory Method Pattern, porque como vimos se trata de reducir la desición de la creación de una instancia a un método, pero que por gusto mío lo pusimos en una clase Factory con un método abstracto. Ahora vamos a hablar del Abstract Factory Pattern, [...]


Related posts:<ol><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/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/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>
</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/abstract-factory-pattern-patrones&amp;text=Abstract 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><a href="http://software.guisho.com/wp-content/uploads/2009/05/factory.jpg"><img class="alignleft size-medium wp-image-124" title="factory" src="http://software.guisho.com/wp-content/uploads/2009/05/factory-199x300.jpg" alt="factory" width="199" height="300" /></a>Hace una semana hablamos del Factory Pattern, que realmente se llama Factory Method Pattern, porque como vimos se trata de reducir la desición de la creación de una instancia a un método, pero que por gusto mío lo pusimos en una clase Factory con un método abstracto. Ahora vamos a hablar del Abstract Factory Pattern, que va un paso más alla: el Abstract Factory Method agrupa varios Factory Methods.</p>
<p>Básicamente lo que hace el este patrón es unir varios Factory Methods, delegando la responsabilidad total sobre qué instancias crear a partir de datos comunes. La semana pasada hicimos un pequeño traductor, que al recibir un número desplegaba su valor en español, inglés o alemán. Para mostrar el concepto del Abstract Factory vamos a extender el ejemplo.<span id="more-86"></span></p>
<p>Primero vamos hacer un sencillo reloj que nos muestra la hora actual. Como sabemos, la hora puede ser desplegada en formato de 24Hrs o puede ser desplegada en formato AM/PM. Recordando que es a manera de ejemplo, vamos a utilizar la clase Date de una manera que no se debe, y probablemente el reloj lo haríamos de una manera más sencilla, pero para nuestro ejemplo queda perfecta su uso. Como en el caso del diccionario, haremos una clase abstracta de Reloj y dos implementaciones para cada una de los formatos, y una clase que contenga el método del Factory Method. La cosa quedaría algo así:</p>
<p>La clase Reloj:</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> Reloj <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #003399;">String</span> dameLaHora<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>La clase que se da la hora en formato AM/PM:</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> RelojAmPm <span style="color: #000000; font-weight: bold;">extends</span> Reloj<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> RelojAmPm<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: #003399;">String</span> dameLaHora<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Date</span> d <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> hora <span style="color: #339933;">=</span> d.<span style="color: #006633;">getHours</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> minutos <span style="color: #339933;">=</span> d.<span style="color: #006633;">getMinutes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> segundos <span style="color: #339933;">=</span> d.<span style="color: #006633;">getSeconds</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> tr<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>hora<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;=</span><span style="color: #cc66cc;">12</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            tr<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;Son las &quot;</span><span style="color: #339933;">+</span>hora<span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">+</span>minutos<span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">+</span>segundos<span style="color: #339933;">+</span><span style="color: #0000ff;">&quot; AM&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            tr<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;Son las &quot;</span><span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>hora<span style="color: #339933;">-</span><span style="color: #cc66cc;">12</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">+</span>minutos<span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">+</span>segundos<span style="color: #339933;">+</span><span style="color: #0000ff;">&quot; PM&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> tr<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>La que nos da la hora en formato de 24 horas:</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> Reloj24Hrs <span style="color: #000000; font-weight: bold;">extends</span> Reloj <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> dameLaHora<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Date</span> d <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> hora <span style="color: #339933;">=</span> d.<span style="color: #006633;">getHours</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> minutos <span style="color: #339933;">=</span> d.<span style="color: #006633;">getMinutes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> segundos <span style="color: #339933;">=</span> d.<span style="color: #006633;">getSeconds</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> tr<span style="color: #339933;">;</span>
        tr <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Son las &quot;</span> <span style="color: #339933;">+</span> hora <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> minutos <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> segundos <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; &quot;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> tr<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Nuestra clase que contiene la el método que elije las instancias. A diferencia del post anterior, ahora el parámetro que recibe el método es un entero, que acepta los enteros especificados como constantes estáticas en la clase. Esto se usa mucho para no estar adivinando los paráemetros que acepta el método:</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> RelojFactory <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> RELOJ_AM_PM<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><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: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> RELOJ_24_HRS<span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> RelojFactory<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> Reloj createReloj<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> tipoDeReloj<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>tipoDeReloj<span style="color: #339933;">==</span>RelojFactory.<span style="color: #006633;">RELOJ_24_HRS</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Reloj24Hrs<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;">if</span> <span style="color: #009900;">&#40;</span>tipoDeReloj<span style="color: #339933;">==</span>RelojFactory.<span style="color: #006633;">RELOJ_AM_PM</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> RelojAmPm<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;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y finalmente la clase cliente, que será la usuario final:</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: #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>
        Reloj r <span style="color: #339933;">=</span> RelojFactory.<span style="color: #006633;">createReloj</span><span style="color: #009900;">&#40;</span>RelojFactory.<span style="color: #006633;">RELOJ_24_HRS</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>r.<span style="color: #006633;">dameLaHora</span><span style="color: #009900;">&#40;</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></pre></div></div>

<p>Hasta aquí tenemos dos fábricas: una de palabras, y la que acabamos de hacer que nos da la hora. En un proyecto cualquiera se nos pide hacer un sistema que despliegue la hora y los números de la manera en la que se expresan en cada país (una implementación súper elemental de Locale de Java). Vamos con dos ejemplos prácticos. En Estados Unidos se despliegan los números en inglés, y la hora en formato AM/PM; mientras que en Guatemala se dicen los números en español y la hora en formato de 24 Horas.</p>
<p>Ahora vamos a crear una Abstract Factory, que le pondremos Locale.</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> AbstractLocaleFactory <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> US<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;ESTADOS_UNIDOS&quot;</span><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: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> GT<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;GUATEMALA&quot;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003399;">String</span> pais<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> Traductor createTraductor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> Reloj createReloj<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getPais<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> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">pais</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: #000066; font-weight: bold;">void</span> setPais<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> pais<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;">pais</span> <span style="color: #339933;">=</span> pais<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Como ven esta fabrica tiene un par de métodos que devuelven un Reloj y un Traductor. Noten que Reloj y Traductor son a su vez clases abstractas.</p>
<p>Ahora implementamos nuestra clase LocaleGuatemalaFactory, que va 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> LocaleGuatemalaFactory <span style="color: #000000; font-weight: bold;">extends</span> AbstractLocaleFactory<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> LocaleGuatemalaFactory<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;">this</span>.<span style="color: #006633;">pais</span><span style="color: #339933;">=</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">GT</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">public</span> Traductor createTraductor<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> 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: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Reloj createReloj<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> RelojFactory.<span style="color: #006633;">createReloj</span><span style="color: #009900;">&#40;</span>RelojFactory.<span style="color: #006633;">RELOJ_24_HRS</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Y la respectiva para Estados Unidos:</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> LocaleEstadosUnidosFactory <span style="color: #000000; font-weight: bold;">extends</span> AbstractLocaleFactory<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> LocaleEstadosUnidosFactory<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;">this</span>.<span style="color: #006633;">pais</span><span style="color: #339933;">=</span>AbstractLocaleFactory.<span style="color: #006633;">US</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Traductor createTraductor<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> TraductorFactory.<span style="color: #006633;">createTraductor</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ingles&quot;</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> Reloj createReloj<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> RelojFactory.<span style="color: #006633;">createReloj</span><span style="color: #009900;">&#40;</span>RelojFactory.<span style="color: #006633;">RELOJ_AM_PM</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ahora en el cliente, si queremos las cosas como se verían en Guatemala, simplemente hacemos esto.</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: #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;
        Reloj reloj <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        Traductor traductor <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
        AbstractLocaleFactory localeFactory <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LocaleGuatemalaFactory<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        reloj <span style="color: #339933;">=</span> localeFactory.<span style="color: #006633;">createReloj</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        traductor <span style="color: #339933;">=</span> localeFactory.<span style="color: #006633;">createTraductor</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;--------&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><span style="color: #0000ff;">&quot;1=&quot;</span><span style="color: #339933;">+</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: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>reloj.<span style="color: #006633;">dameLaHora</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>El resultado de correr el codigo anterior es:<br />
<strong><br />
1=uno<br />
Son las 21:50:17<br />
</strong></p>
<p>Ahora si cambiamos la linea</p>

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

<p>Por esta</p>

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

<p>Tendremos como resultado:<br />
<strong><br />
1=one<br />
9:52:56 PM<br />
</strong></p>
<p>Aquí es un ejemplo sencillo. Pero imaginen quedemos hacer un Locale para cada país, y en el locale tener más cosas como: la nomenclatura de moneda, el sistema de numeración, el manejo de fechas, kilómetros o millas, etc. Con el Abstract Factory Pattern es muy sencillo agregar cada nuevo pais, o cada nueva característica del Locale. Pero sobre todo el código es MUY legible y FACILMENTE extensible. Alguien que nunca ha visto estas piezas de código puede entender como hacer un nuevo país.</p>
<p>Entonces, el Abstract Factory Pattern puede ayudarnos mucho en casos donde hemos de manejar familias de objetos. Al inicio no siempre es obvia su implementación, pero siempre está el recurso de del refactoring, en el cual salen nuevas maneras sencillas de hacer las cosas. Este, como muchos patrones, requieren escribir un poco más de código al principio, pero nos reducen el esfuerzo a largo plazo porque hay menos código repetido.</p>
<p><a href="http://software.guisho.com/wp-content/uploads/2009/05/abstractfactory.zip">Aquí el código</a> de este patró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/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/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/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>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://software.guisho.com/abstract-factory-pattern-patrones/feed</wfw:commentRss>
		<slash:comments>8</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>
		<item>
		<title>Patrones de Diseño</title>
		<link>http://software.guisho.com/patrones-de-diseno</link>
		<comments>http://software.guisho.com/patrones-de-diseno#comments</comments>
		<pubDate>Tue, 21 Apr 2009 22:07:24 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[patrones]]></category>

		<guid isPermaLink="false">http://software.guisho.com/?p=38</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&amp;text=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>
Patrones de Diseño (Design Patterns) A partir de ahora comenzaremos todos los martes con un nuevo patrón de diseño. ¿Qué son los patrones de diseño? Bueno, durante el tiempo que el paradigma de programación orientado a objetos ha estado por ahí, se han aprendido muchas cosas. Muchas de las lecciones aprendidas se han tratado de [...]


Related posts:<ol><li><a href='http://software.guisho.com/patrones-estructurales-structural-patterns' rel='bookmark' title='Permanent Link: Patrones estructurales (structural patterns)'>Patrones estructurales (structural patterns)</a></li>
<li><a href='http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno' rel='bookmark' title='Permanent Link: Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño'>Patron Adaptador &#8211; Pattern Adapter &#8211; 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&amp;text=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/04/image9294.jpg"><img class="alignleft size-medium wp-image-130" title="image9294" src="http://software.guisho.com/wp-content/uploads/2009/04/image9294-300x292.jpg" alt="image9294" width="300" height="292" /></a>Patrones de Diseño (Design Patterns)</p>
<p>A partir de ahora comenzaremos todos los martes con un nuevo patrón de diseño. ¿Qué son los patrones de diseño? Bueno, durante el tiempo que el paradigma de programación orientado a objetos ha estado por ahí, se han aprendido muchas cosas. Muchas de las lecciones aprendidas se han tratado de conceptualizar. El primer esfuerzo se le debe a la conocida como Gang Of Four (GoF), quienes fueron los primeros en acuñar el término. </p>
<p><span id="more-38"></span></p>
<p>Los patrones de diseño son un conjunto de estrategias, o buenas prácticas, que pueden facilitar el trabajo en muchas situaciones a la hora de realizar una aplicación orientada a objetos (según la RAE utilizo de mala manera el término &#8220;aplicación&#8221;). Los patrones de diseño son relativamente fáciles de comprender, no son nada del otro mundo. Lo que a veces se hace complejo es utilizarlos. Por ello hay que conocerlos bien, especialmente los más importantes, porque realmente facilitan el trabajo, y sobre todo, hacen el código más legible. </p>
<p>Los patrones de diseño son independientes del lenguaje en el que utilicen (siempre y cuando el lenguaje sea orientado a objetos!). Generalmente se presentan como diagramas de UML. Una lista completa la pueden encontrar en <a href="http://es.wikipedia.org/wiki/Patrón_de_diseño">wikipedia</a>. </p>
<p>Según su enfoque los patrones de diseño se agrupan en:</p>
<ul>
<li>Patrones de creación (o creacionales). </li>
<li>Patrones estructurales. </li>
<li>Patrones de  comportamiento.</li>
<li>Patrones de sistema. </li>
</ul>
<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/patrones-estructurales-structural-patterns' rel='bookmark' title='Permanent Link: Patrones estructurales (structural patterns)'>Patrones estructurales (structural patterns)</a></li>
<li><a href='http://software.guisho.com/patron-adaptador-pattern-adapter-patrones-de-diseno' rel='bookmark' title='Permanent Link: Patron Adaptador &#8211; Pattern Adapter &#8211; Patrones de diseño'>Patron Adaptador &#8211; Pattern Adapter &#8211; 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/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

