




<?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; factory pattern</title>
	<atom:link href="http://software.guisho.com/software/factory-pattern/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>Factory Pattern &#8211; Patrones</title>
		<link>http://software.guisho.com/patrones-de-diseno-factory-pattern</link>
		<comments>http://software.guisho.com/patrones-de-diseno-factory-pattern#comments</comments>
		<pubDate>Tue, 28 Apr 2009 22:57:49 +0000</pubDate>
		<dc:creator>guisho (Luis H. Fernandez)</dc:creator>
				<category><![CDATA[Buenas prácticas - Mejores Prácticas]]></category>
		<category><![CDATA[Patrones Creacionales]]></category>
		<category><![CDATA[Patrones de diseño]]></category>
		<category><![CDATA[factory pattern]]></category>
		<category><![CDATA[patrón de fábrica]]></category>
		<category><![CDATA[patrones]]></category>
		<category><![CDATA[patrones creacionales]]></category>

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

