You are on page 1of 5

29/10/13

Design Pattern Strategy | uaiHebert

(:

Portugus

English

Studied books

About Me

Contact Me

[Curriculum Vitae]

Design Pattern Strategy


December 9, 2010 2:15 pm | Leave a Comment | uaihebert

SEARCH
Search

Hello, how are you? I will post here some design patterns of the study I am doing about this subject. The base book to this study will be Head First Design Patterns. I will describe in here the same patterns that we can find in the book, but I will be using different samples and adding more material about this subject as soon it is possible. Let us use this user case: An internet site that sells toys cars is receiving a lot of customer visitors every day and becoming more famous. Its investors want more; they want that the site provides to the customers the simulations of the toy car actions. Check below our class model (there are others sub classes of ToyCar that are not described below):

Enter your email address:

Subscribe Delivered by FeedBurner (Google)

Subscribe via RSS

Meu livro JSF (Portuguese Only)

CATEGORIES
Business English (25) Business Portugus (25) Certificao Portugus (1) The investors want that the car perform the action of starting the engine, to the customers may hear the engine sound. To accomplish this, the solution that it is the most useful, fastest and quickest may be to apply some changing in the super class. What of bad could come of using this solution that the Java gives us? Any change in the super class ToyCar will be reflected to all sub classes, and all sub classes will have the same behavior! We just have to create a method to start the engine (startEngine()) and our problem will be solved: Certification English (1) Clean Code [English] (5) Cdigo Limpo [Portugus] (5) Design Pattern English (3) Design Pattern - Observer (Part 01) Design P at t ern - St rat egy Design Pattern Observer (Part 02) Design Pattern Portugus (3) English (58) OO Paterns [English] (2) OO Paterns [Portugus] (2) Portugus (58) Aplicao Web Completa JSF EJB JPA JAAS The team was very happy with the result of this new functionality that was delivered on time. Now the customers can hear the engine sound. BUT, after a phone call it was possible to see that something bad happened. One of the investors saw something in our application that should never happen, a wood car starting its engine. Why this happened? Let us see our model: Aplicao Web Completa Tomcat JSF Primefaces JPA Hibernate Autenticao de Usurios (Filter/Servlet) Auto Create Schema Script com: Ant, Hibernate 3 e JPA 2 Cobrindo seus testes com Cobertura, JUnit, HSQLDB, JPA Cdigo Limpo - Parte 04

uaihebert.com/?p=26

1/5

29/10/13

Design Pattern Strategy | uaiHebert

(:
Cdigo Limpo - Parte 05 Cdigo Limpo Parte 01 Cdigo Limpo Parte 02 Cdigo Limpo Parte 03 Como agendar sua certificao Java Oracle Como testar sua JPQL / HQL sem realizar Deploy Criando um WebServer Design Pattern - Observer (Parte 01) Design Pattern - Observer (Parte 02) Design Pattern - Strategy Diga, no pergunte! EasyCriteria - Novas funcionalidades

Our wood car, that also has ToyCar as super class, received the method to start the engine when a wood car does not have an engine. What could we do to solve this problem? We could just override the method: 1 2 3 4 @ O v e r r i d e < f o n t > < / f o n t > p u b l i cb o o l e a ns t a r t E n g i n e ( ){ < f o n t > < / f o n t > / /D on o t h i n g < f o n t > < / f o n t > }

EasyCriteria - Utilizando a Criteria do JPA de um modo simples EasyCriteria 2.0 - JPA Criteria tem que ser simples EasyCriteria 3.0 - Novas funcionalidades EasyCriteria no Maven JPA @ManyToMany Unidirecional e Bidirecional JPA @OneToMany e @ManyToOne Unidirecional e Bidirecional JPA @OneToOne Unidirecional e Bidirecional JPA Consultas e Dicas JPA Mapeando Datas (Date) e Enum JPA Mapeando Duas Tabelas em uma Classe JPA Mini Livro - Primeiros passos e conceitos detalhados JPA SequenceGenerator JPA TableGenerator - Chave Primria Simples JPA Uma Tabela por Classe JPA Uma tabela por herana JPA: Ordernando listas e utilizando Map como atributo mapeado JSF - Hello World, AutoComplete JSF Exemplos Simples com Ajax JSF Exibindo Objeto e Mensagens aps Redirect JSF Mini Livro - Dicas, conceitos e boas prticas JSF Parametros por Get Request RESTFull JSF: Converter e Bean Auto Complete JUDCon 2013 Brasil JUnit com HSQLDB, JPA e Hibernate Lanado EasyCriteria 1.0 Lanado meu primeiro livro: JSF Eficaz Lei de Demeter O Pai do Java usa Jelastic Obrigado DZone

Would the above code be the best solution? Let us suppose that we have a sub class of ToyCar, a metal car (MetalCar) where we would have to override the method too. By doing this method overriding in all classes methods we are increasing our project complexity. And each time, that a new ToyCar sub class is created and this sub class should not have the method startEngine() implemented, we would have to override this method also. So, which solution would be the best one here? Let us apply the first pattern principle of this study: I dent ify ev ery t hing t hat changes and isolat e it from what does not change. What is the meaning of this? Think about an engine behavior that will be present in one class and other different engine behavior that should be present in another class; we could isolate this behavior from our ToyCar class. Instead of letting our class ToyCar handling this behavior, why do not delegate it? Here it come our second pattern principle: P rogram t o an int erface This principle is nothing more than: use all benefits from super class. Imagine if we have an interface with a visible method, our class will not care with which behavior the interface method has. Let us create an interface to handle this engine behavior:

uaihebert.com/?p=26

2/5

29/10/13

Design Pattern Strategy | uaiHebert

(:
Paginao de Datatable Lazy com JSF (Primefaces) Quatro solues para LazyInitializationException Review do Livro: Instant PrimeFaces Starter TDC 2013 - Minhas Palestras TDD - Primeiros passos TDD Cobertura de testes com JUnit Ant e Emma Tratando Excees em uma Aplicao Web Tutorial Hibernate 3 com JPA 2 Tutorial JPA Chave Primria Composta uaiHebert no JUDCON Brasil 2013 Validao de Login de Usurio com JSF e JAAS TDD [English] (4) TDD [Portugus] (4) Web App [English] (14) Web App [Portugus] (14)

ARCHIVES
Bellow you can check how our classes will be implemented. First the class ToyCar, then Mercedes and WoodCar: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 / /I n t e r f a c ea n dE n g i n eB e h a v i o ri m p l e m e n t a t i o n s < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i ci n t e r f a c eE n g i n e B e h a v i o r{ < f o n t > < / f o n t > p u b l i cb o o l e a ns t a r t E n g i n e ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cc l a s sN o E n g i n e B e h a v i o ri m p l e m e n t sE n g i n e B e h a v i o r{ < f o n t > < / f o n t > < f o n t > < / f o n t > @ O v e r r i d e < f o n t > < / f o n t > p u b l i cb o o l e a ns t a r t E n g i n e ( ){ < f o n t > < / f o n t > S y s t e m . o u t . p r i n t l n ( " N oe n g i n et ot u r no n " ) ; < f o n t > < / f o n t > r e t u r nt r u e ; < f o n t > < / f o n t > } < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cc l a s sR e g u l a r E n g i n e B e h a v i o ri m p l e m e n t sE n g i n e B e h a v i o r{ < f o n t > < / f o n t > < f o n t > < / f o n t > @ O v e r r i d e < f o n t > < / f o n t > p u b l i cb o o l e a ns t a r t E n g i n e ( ){ < f o n t > < / f o n t > S y s t e m . o u t . p r i n t l n ( " E n g i n eO n " ) ; < f o n t > < / f o n t > r e t u r nt r u e ; < f o n t > < / f o n t > } < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cc l a s sP o w e r f u l E n g i n e B e h a v i o ri m p l e m e n t sE n g i n e B e h a v i o r{ < f o n t > < / f o n t > < f o n t > < / f o n t > @ O v e r r i d e < f o n t > < / f o n t > p u b l i cb o o l e a ns t a r t E n g i n e ( ){ < f o n t > < / f o n t > S y s t e m . o u t . p r i n t l n ( " P o w e r f u l lE n g i n eO n " ) ; < f o n t > < / f o n t > r e t u r nt r u e ; < f o n t > < / f o n t > } < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > / /O u rC l a s s e sI m p l m e n t a t i o i n s < f o n t > < / f o n t > p u b l i cc l a s sT o y C a r{ < f o n t > < / f o n t > p r i v a t ei n td o o r T o t a l ; < f o n t > < / f o n t > p r i v a t ei n tm a x S p e e d ; < f o n t > < / f o n t > p r o t e c t e dE n g i n e B e h a v i o re n g i n e B e h a v i o r ; < f o n t > < / f o n t > / /O t h e r sa t t r i b u t e s < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cT o y C a r ( ) { < f o n t > < / f o n t > e n g i n e B e h a v i o r=n e wR e g u l a r E n g i n e ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cv o i ds t a r t E n g i n e ( ) { < f o n t > < / f o n t > e n g i n e B e h a v i o r . s t a r t E n g i n e ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > / /O t h e r sm e t h o d s < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cc l a s sM e r c e d e se x t e n d sT o y C a r{ < f o n t > < / f o n t >

[+] 2013 (20) [+] 2012 (24) [+] 2011 (46) [+] 2010 (26)

UNIQUE VISITORS

uaihebert.com/?p=26

3/5

29/10/13
5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4

Design Pattern Strategy | uaiHebert


< f o n t > < / f o n t > p u b l i cM e r c e d e s ( ) { < f o n t > < / f o n t > e n g i n e B e h a v i o r=n e wP o w e r f u l E n g i n e B e h a v i o r ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > @ O v e r r i d e < f o n t > < / f o n t > p u b l i cv o i ds t a r t E n g i n e ( ) { < f o n t > < / f o n t > e n g i n e B e h a v i o r . s t a r t E n g i n e ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cc l a s sW o o d C a re x t e n d sT o y C a r{ < f o n t > < / f o n t > < f o n t > < / f o n t > p u b l i cW o o d C a r ( ) { < f o n t > < / f o n t > e n g i n e B e h a v i o r=n e wN o E n g i n e B e h a v i o r ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > < f o n t > < / f o n t > @ O v e r r i d e < f o n t > < / f o n t > p u b l i cv o i ds t a r t E n g i n e ( ) { < f o n t > < / f o n t > e n g i n e B e h a v i o r . s t a r t E n g i n e ( ) ; < f o n t > < / f o n t > } < f o n t > < / f o n t > }

(:

I know that we could change the way that our interface is receiving its implementation ( engineBehavior = new NoEngineBehavior();) and another upgrades about patterns, but this refactoring is subject to another posts. You may think: Wait a minute, even if I do comment the method startEngine() or put the code engineBehavior = new NoEngineBehavior(); I still have duplicated code in my system! Think with me about this next investor requirement: When we call the method startEngine() in a type of ToyCar that does not have an engine, we would have to register this action in a log. If you notice how our classes are implemented now (WoodCar, and all others MetalCar, BambooCar), we would have to change only the method startEngine() in our class NoEngineBehavior. All classes that do not have an engine behavior would be with a correct functioning. Final considerations: The class name should indicate a noun. Things like: Car, House, Computer, etc. In the user case that we simulated today this behavior is like our noun. It is a class that handles a behavior pattern. Program to an interface this principle does not necessarily means that we have to create an Interface, but it means always program to a super type. You should always program to a super type like a regular Class (POJO), Abstract Class and Interface. You must decide the best type for your system and implement it. In the book Head First Design Patterns the authors make this explanation very clear. Do not mistake this principle that says: always code for a super type with always create an interface. A super type will be the best solution to your design problems in like 99% of the situations. We just studied another project Principle: Give priority to composition rather than inheritance. As we saw in our user case today, we used an interface to create the composition. Using composition in our system will make our job easier. Design Pattern: Strategy Studied Principles: Identify everything that changes and isolate it from what does not change. Program to an interface. Give priority to composition rather than inheritance. I hope this post might be able to help you. If you have any questions or ideas to share just leave your comment. See you soon.
Posted in: Design Pattern - English, English

uaihebert.com/?p=26

4/5

29/10/13

Design Pattern Strategy | uaiHebert

(:

Leave a Reply
Your email address will not be published. Required fields are marked * Name *

Email *

Website

CAPTCHA Code *

Post Comment Notify me of follow-up comments by email. Notify me of new posts by email.

Previous Post

Next Post

Copyright 2013 - uaiHebert

(:

Chip Life Theme by TutorialChip WordPress

Sh a r e:

uaihebert.com/?p=26

5/5

You might also like