<?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>cObaia.net &#187; design patterns</title>
	<atom:link href="http://cobaia.net/categorias/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://cobaia.net</link>
	<description>PHP, Javascript and some code around it!</description>
	<lastBuildDate>Sun, 29 Jan 2012 03:56:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Forget the evil C of MVC inside the CakePHP</title>
		<link>http://cobaia.net/2012/01/forget-the-evil-c-of-mvc-inside-the-cakephp/</link>
		<comments>http://cobaia.net/2012/01/forget-the-evil-c-of-mvc-inside-the-cakephp/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 03:56:40 +0000</pubDate>
		<dc:creator>Vinícius Krolow</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://cobaia.net/?p=823</guid>
		<description><![CDATA[CakePHP is great, I love this framework, it&#8217;s really fast to develop and it&#8217;s possible to maintain a great code inside this framework, I like the rules that CakePHP impose, I like that CakePHP is an obstructive framework, it makes easy to training the team, and put new members inside the team, and to everyone keep one [...]]]></description>
			<content:encoded><![CDATA[<p>CakePHP is great, I love this framework, it&#8217;s really fast to develop and it&#8217;s possible to maintain a great code inside this framework, I like the rules that CakePHP impose, I like that CakePHP is an obstructive framework, it makes easy to training the team, and put new members inside the team, and to everyone keep one standard.</p>
<p>BUT, one problem that comes not just with CakePHP but with several frameworks, is the usage of the Model. it&#8217;s not really a problem, but I think that is the way that people learned MVC with the framework, and the way that we see the Controller.</p>
<p>Frameworks, such as CakePHP, Rails and so on, impose that Model is database access (not really, but they come with this access).</p>
<p>Is that wrong? NOT really wrong&#8230;</p>
<p>As the fact that normally your application will need to save data into one database, or filesystem, etc&#8230; So provide one database access inside our model probably will help us.</p>
<h3>What is the problem?</h3>
<p>The problem comes when you see your model as JUST one database access layer, see the model as the thing that will store our data. So we start write the system logic inside the Controller, and this Controller starts to grow, because it already has several roles in our application, it handle the request, it handle the input, it call the model, it call the view&#8230; and it also get an additional role that is have the system logic. So our controller get FAT, hard to maintain, hard to change, hard to test, hard to change. It start to has the action methods, some other private/protected methods to implement logic, and it get ugly, strange, BIG.</p>
<h3>What about our model?</h3>
<p>The model keep thin, with no methods, no logic, just with the relationships of our database, with the validation&#8230; does it seems strange for you?</p>
<p><strong>So what hell we are not using our model?</strong></p>
<p>YES, we should use our model to make the logic of the system, is that the M of our application, is what Model must be, and is what the Model is expecting.</p>
<h3>How we can start use our model as the logic part of our applications?</h3>
<ol>
<li>STOPING to see the Model as your database access;</li>
<li>Writing methods inside our models;</li>
<li>Creating models without usage of database;</li>
<li>Making the models talks each other;</li>
<li>Importing libraries, objects inside or model;</li>
<li>Creating one API inside or models, to make easy the calls for the controllers;</li>
<li>Make your controllers as  much thin as possible.</li>
</ol>
<h3>What will be your gains?</h3>
<ol>
<li>You will probably have more freedom to make your logic;</li>
<li>Your code will be more simple to maintain;</li>
<li>It&#8217;s simple to write test for Models;</li>
<li>You will have a better OO structure of your logic;</li>
<li>You will start think different about Behaviors, Components in CakePHP;</li>
<li>Your controller will be thin, and make just what he should do, nothing else;</li>
<li>You will stop rewrite code, the model can be called in any controller that you want;</li>
<li>With a good structure of logic, it will be so much easy to upgrade your code to new versions of  the framework, or why not, migrate to another framework, as the fact that your logic system will not depends more of the features that CakePHP has.</li>
</ol>
<p>To summarize, CakePHP is great, it has great tools to make our development fast, but what we can not do is misunderstand the MVC, and starts to be addict with bad practices.  Frameworks like Zend make it more simple to understand, because it not provides directly in the model one database access, BUT anyway in CakePHP we can make the thing correct too, and get everything good of the framework.</p>
<p>So the idea behind the post is not forget the Controller, but pay much more attention in your Model.</p>
]]></content:encoded>
			<wfw:commentRss>http://cobaia.net/2012/01/forget-the-evil-c-of-mvc-inside-the-cakephp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Padrões de Projeto os Design Patterns: Padrão Factory</title>
		<link>http://cobaia.net/2009/01/padroes-de-projeto-os-design-patterns-padrao-factory/</link>
		<comments>http://cobaia.net/2009/01/padroes-de-projeto-os-design-patterns-padrao-factory/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 20:10:21 +0000</pubDate>
		<dc:creator>Vinícius Krolow</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[programação]]></category>

		<guid isPermaLink="false">http://cobaia.net/?p=366</guid>
		<description><![CDATA[Dando continuidade aos designer patterns, vou falar um pouco hoje do Designer Factory. Uma definição para o Factory seria, definir uma interface única para criação de objetos, deixando a cargo da classe Factory decidir qual instância de subclasse deve ser feita. Trocando em miudos, é como uma central telefonica, você liga para apenas 1 número [...]]]></description>
			<content:encoded><![CDATA[<p>Dando continuidade aos <a href="http://cobaia.net/categorias/design-patterns/">designer patterns</a>, vou falar um pouco hoje do Designer Factory.</p>
<p>Uma definição para o Factory seria, definir uma interface única para criação de objetos, deixando a cargo da classe Factory decidir qual instância de subclasse deve ser feita.</p>
<p>Trocando em miudos, é como uma central telefonica, você liga para apenas 1 número que você conhece, pergunta para a telefonista o que deseja, e ele te retorna o número correspondido ao seu pedido.</p>
<p>É bastante comum encontrarmos esse padrão em frameworks, ferramentas e bibliotecas.</p>
<p>Bom vamos ao um exemplo prático pois por enquanto está tudo lindo, sabemos que podemos encapsular subclasses em uma classe, fornecendo assim uma instância única, logo se num futuro é necessário fazer alterações, precisamos mudar em apenas um local.</p>
<p>Jõao um famoso empresário da cidade, decide criar uma lancheria, então logo vai para o seu sobrinho dono de uma empresa de programação na cidade e passa os requisitos, nada mais que 1 cardápio com os preços dos lanches tendo 3 tipos de lanches, X-Gordura, X-Maionese, X-Ovo, cada 1 com 1 preço diferente.</p>
<p>José que também é sobrinho do Jõao, diz logo para os programdores tarefa simples, criamos 1 classe que armazena o lanche e receba como parâmetro o preço&#8230;</p>
<p>Todos concluem ser uma ótima solução até que depois da entrega, Jõao resolve alterar o preço de 1 dos lanches, para concorrer com outra lancheria que abriu nas proximidades. Pede ao seu sobrinho para alterar o preço do lanche.</p>
<p>E o sobrinho disse que demoraria 6 meses, para fazer isso&#8230; José envocado, mas como se para fazer o programa todo demorou 2 meses&#8230;</p>
<p>Seu sobrinho responde é que vou ter que alterar os 200 códigos onde está o preço desse lanche!</p>
<p>Conclusão! menos é mais, e é isso que ocorre, vamos fazer essa simples implementação da lancheria com o Padrão Factory.</p>

<div class="wp_codebox"><table><tr id="p3663"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
</pre></td><td class="code" id="p366code3"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span> ?php
abstract <span style="color: #000000; font-weight: bold;">class</span> Lanche <span style="color: #009900;">&#123;</span>
    abstract <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<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;">class</span> XgorduraLanche <span style="color: #000000; font-weight: bold;">extends</span> Lanche <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color:#800080;">2.90</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;">class</span> XmaioneseLanche <span style="color: #000000; font-weight: bold;">extends</span> Lanche <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color:#800080;">3.90</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;">class</span> XovoLanche <span style="color: #000000; font-weight: bold;">extends</span> Lanche <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color:#800080;">6.90</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;">class</span> LancheFactory <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> lanche<span style="color: #009900;">&#40;</span><span style="color: #000088;">$type</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$type</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'Xgordura'</span><span style="color: #339933;">:</span>
                <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> XgorduraLanche<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'Xmaionese'</span><span style="color: #339933;">:</span>
                <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> XmaioneseLanche<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
                <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> XovoLanche<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: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xgordura'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xmaionese'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xovo'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Como podemos ver foi muito simples a implementação, criamos uma classe abstrata onde dizemos quais são os métodos que temos que implementar nos tipos de lanches, criamos os diversos tipos de lanches extendendo ele da classe abstrata, logo após fizemos a classe factory, com 1 método statico que passamos como parâmetro o tipo do lanche que queremos, dentro do método temos 1 controle com um block swich, e por fim retorna o preço de cada tipo de lanche.</p>
<p>O que pode ser feito é não usar o controle com switch e chamar dinâmicamente a classe, além de adicionar um tratamento de erro para evitar quando informado o tipo errado:</p>

<div class="wp_codebox"><table><tr id="p3664"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
</pre></td><td class="code" id="p366code4"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span> ?php
abstract <span style="color: #000000; font-weight: bold;">class</span> Lanche <span style="color: #009900;">&#123;</span>
    abstract <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<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;">class</span> XgorduraLanche <span style="color: #000000; font-weight: bold;">extends</span> Lanche <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color:#800080;">2.90</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;">class</span> XmaioneseLanche <span style="color: #000000; font-weight: bold;">extends</span> Lanche <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color:#800080;">3.90</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;">class</span> XovoLanche <span style="color: #000000; font-weight: bold;">extends</span> Lanche <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> pegar_preco<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color:#800080;">6.90</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;">class</span> LancheFactory <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> lanche<span style="color: #009900;">&#40;</span><span style="color: #000088;">$type</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$type</span> <span style="color: #339933;">.=</span> <span style="color: #0000ff;">'Lanche'</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><a href="http://www.php.net/class_exists"><span style="color: #990000;">class_exists</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$type</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000088;">$type</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: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Nao tem essa classe!!'</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: #009900;">&#125;</span>
&nbsp;
try <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xpicanha'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Informamos que não temos esse pedido no nosso cardápio! &lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
try <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xgordura'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Informamos que não temos esse pedido no nosso cardápio! &lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
try <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xovo'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Informamos que não temos esse pedido no nosso cardápio! &lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
try <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$lanche</span> <span style="color: #339933;">=</span> LancheFactory<span style="color: #339933;">::</span><span style="color: #004000;">lanche</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Xmaionese'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$lanche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pegar_preco</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Informamos que não temos esse pedido no nosso cardápio! &lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Esse foi um exemplo simples, mas em prática podemos se deparar em boa  hora de usar o Factory, como tratamento de diversos tipos, como por exemplo imagens, arquivos de música, até mesmo banco de dados entre outros.</p>
<p>Qualquer dúvida comentem!</p>
]]></content:encoded>
			<wfw:commentRss>http://cobaia.net/2009/01/padroes-de-projeto-os-design-patterns-padrao-factory/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Padrões de Projeto os Design Patterns: Padrão Singleton</title>
		<link>http://cobaia.net/2008/10/padroes-de-projeto-os-design-patterns-padrao-singleton/</link>
		<comments>http://cobaia.net/2008/10/padroes-de-projeto-os-design-patterns-padrao-singleton/#comments</comments>
		<pubDate>Thu, 16 Oct 2008 14:13:54 +0000</pubDate>
		<dc:creator>Vinícius Krolow</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[programação]]></category>

		<guid isPermaLink="false">http://cobaia.net/?p=292</guid>
		<description><![CDATA[Vou começar hoje uma série de post&#8217;s, voltadas para os programadores, vou passar alguns padrões de projetos a serem utilizados. Mas afinal o que são padrões de projeto? Padrões de Projetos ou Design Patterns, são características arquiteturais de software, que ao longo do tempo se tornaram soluções de problemas. Ou seja, você tem um problema, [...]]]></description>
			<content:encoded><![CDATA[<p>Vou começar hoje uma série de post&#8217;s, voltadas para os programadores, vou passar alguns padrões de projetos a serem utilizados.</p>
<p><strong>Mas afinal o que são padrões de projeto?</strong></p>
<p><a href="http://pt.wikipedia.org/wiki/Padr%C3%B5es_de_projeto_de_software">Padrões de Projetos</a> ou Design Patterns, são características arquiteturais de software, que ao longo do tempo se tornaram soluções de problemas. Ou seja, você tem um problema, muitas vezes outras pessoas já passaram por ele, logo, alguém já resolveu ele. Com isso, com problemas freqüentes de arquitetura na programação que os padrões de projetos surgiram.</p>
<p>Eles são, soluções muito boas, que várias pessoas ajudaram a pensar na melhor solução, para problemas existentes.</p>
<p>Bom mas chega desse papo, deixa um pouco mais da história, para um próximo post&#8230;</p>
<p>Vamos por a mão na massa, opa, massa não, pois dessa vez não é <a href="http://cakephp.org">CakePHP</a>. Bom chega de piadinhas sem graça, vamos ao primeiro padrão de projeto a ser apresentado.</p>
<p><strong>É ele o Singleton</strong>.</p>
<p>Ao que se refere o Singleton, o seu nome é bem sugestivo, Singleton é aquele padrão que garante apenas 1 instância de 1 classe, ou seja ele garante que após instanciar uma vez a classe, você sempre irá estar usando o mesmo objeto.</p>
<p><strong>Hmmm, legal mas quando usar???</strong></p>
<p>Em todos os lugares, onde se precisa garantir uma instancia de uma classe, ou seja, por exemplo 1 log de dados, onde apenas um objeto da aplicação é responsável pelo controle dos log&#8217;s. Outro exemplo, é uma conexão de banco de dados, que no caso seja necessário garantir sempre a mesma conexão. Entre outros exemplos.</p>
<p><strong>Bom vamos ao exemplo da implementação, em PHP:</strong></p>

<div class="wp_codebox"><table><tr id="p2926"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code" id="p292code6"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>?php
<span style="color: #000000; font-weight: bold;">class</span> Singleton <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000088;">$instance</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//atributo responsável por retornar a instancia da classe.</span>
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000088;">$cont</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//atributo que serve apenas para contar quantas vezes a classe foi chamada.</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	* Método construtor responsável por criar a página, é declarado como privado para garantiar,
	* que apenas a classe Singleton chame ele!
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&amp;lt;h1&amp;gt;Sou sempre o mesmo, com a mesma instancia!&amp;lt;/h1&amp;gt;
&quot;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Texto para mostrar quando ocorre a instancia e comprovar que só ocorre uma vez!</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">/*
	* Método singleton, responsável por ser o construtor da classe, por ser abstrato e público,
	* é possível chamar ele sem termos o objeto da classe Singleton;
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> singleton<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;">//Verifica se o atributo $instance já foi setado, caso não faz a instancia dele</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><a href="http://www.php.net/isset"><span style="color: #990000;">isset</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">//Criamos o objeto e alocamos ele para o atributo self::$instance</span>
			<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Singleton<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: #666666; font-style: italic;">//Código para mostrar quantas instancias requiridas da classe tivemos, e que é sempre o mesmo objeto</span>
		<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$cont</span><span style="color: #339933;">++;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;e fui chamado &quot;</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$cont</span> <span style="color: #339933;">,</span><span style="color: #0000ff;">&quot; vezes.&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//Retorna a instancia da classe!</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$instance</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span> 
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//5 chamadas do objeto singleton</span>
Singleton<span style="color: #339933;">::</span><span style="color: #004000;">singleton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Singleton<span style="color: #339933;">::</span><span style="color: #004000;">singleton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Singleton<span style="color: #339933;">::</span><span style="color: #004000;">singleton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Singleton<span style="color: #339933;">::</span><span style="color: #004000;">singleton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Singleton<span style="color: #339933;">::</span><span style="color: #004000;">singleton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
?<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Acho que os comentários estão explicando bem o funcionamento, mas vamos tentar explicar um pouco mais, se temos que garantir apenas 1 objeto, não podemos ter o método construtuor liberado para novas instancias, logo criamos um novo método singleton, este passa a ser o responsável por criar um novo objeto, caso seja a preimeira instancia ou retornar o objeto que já foi instanciado.</p>
<p>Bom por hoje é isso, vou continuar a explicar em PHP alguns Designer Patterns.</p>
]]></content:encoded>
			<wfw:commentRss>http://cobaia.net/2008/10/padroes-de-projeto-os-design-patterns-padrao-singleton/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

