You are on page 1of 23

Lições Aprendidas

Design Patterns
Agenda
• Definições
• Princípios
• Anti-padrões
• Padrões de projeto
– Bridge
– Observer
Design Patterns
Definição

“Cada padrão descreve um problema que ocorre


freqüentemente em seu ambiente, e então descreve
o núcleo de uma solução para o problema, de
maneira que você possa usar esta solução um
milhão de vezes, sem fazê-la do mesmo jeito duas
vezes.”
Christopher Alexander (Arquiteto e
Urbanista), 1977

“Um padrão é a abstração de uma forma concreta que


ocorre muitas vezes em contextos não arbitrários
específicos”
Riehle and Zullighoven, 1996

“Resolve um problema. É um conceito provado. A


Design Patterns
Características
• Algo comprovado que captura e comunica os
conhecimentos das melhores práticas

• Descoberto, não inventado

• Soluções Sucintas e de Fácil Aplicação


• Capturam, de forma sucinta e facilmente aplicável,
soluções de projeto de programas de computador que
foram desenvolvidas e evoluíram com o passar do
tempo

• Soluções Exaustivamente Refinadas


• Resultados de um longo processo de projeto, re-
projeto, teste e reflexão sobre o que torna um sistema
mais flexível, reusável, modular e compreensível

• Soluções Compartilhadas
• Construídas em grupo
Design Patterns
Três princípios de problemas
Agile Software Development: Principles, Patterns, and Practices by Robert Martin

• Rigidez
Dificuldade de mudança visto que cada mudança afeta muitas partes
do sistema

• Fragilidade
Após fazer uma mudança, alguns outros módulos do sistema passam
a não funcionar

• Imobilidade
Dificuldade de reuso em outro aplicativo
Design Patterns
Princípios
• Open Close Principle
“Open for extension but closed for modifications”

• Single Responsibility Principle


“A class should have only one reason to change”

• Dependency Inversion Principle


“High-level modules should not depend on low-level modules. Both should
depend on abstractions. Abstractions should not depend on details. Details
should depend on abstractions”

• Interface Segregation Principle


“Clients should not be forced to depend upon interfaces that they don't use”
abstractions”

• Liskov's Substitution Principle


“Derived types must be completely substitutable for their base types”
Design Patterns
Princípios

• Open Close Principle


“Open for extension but closed for modifications”
Design Patterns
Open Close Principle
• Single Responsibility Principle
“A class should have only one reason to change”
Design Patterns
Princípios
• Dependency Inversion Principle
“High-level modules should not depend on low-level modules. Both
should depend on abstractions. Abstractions should not depend on
details. Details should depend on abstractions”
Design Patterns
Princípios
• Interface Segregation Principle
“Clients should not be forced to depend upon interfaces that they don't
use”
abstractions”
Design Patterns
Princípios
• Liskov's Substitution Principle
“Derived types must be completely substitutable for their base types”
Anti Design Patterns
Desenvolvimento

• Blob
Quando uma classe domina a nossa aplicação

• Lava Flow
Fragmentos de código que fluem vagamente numa
aplicação com o decorrer do tempo

• Poltergeists (proliferação de classes)


Um poltergeist é uma classe pequena com poucas
referências e é instanciada por um período muito curto

• Golden Hammer
Conhecedor de apenas uma técnica X e molda cada
problema até que estes se encaixam no seu padrão X

• Spaghetti Code
Sistemas com pouca estrutura, com um número reduzido
de classes e métodos grandes
Anti Design Patterns
Arquiteturais

• Vendor Lock-In
Construção de sistemas que são altamente dependentes de interfaces
proprietárias

• Design by Committee
Muita gente trabalhando junto para projetar a mesma arquitetura sem um
método bem organizado. Conseqüência: arquitetura excessivamente
complexa para atender a todas as diferentes opiniões e pontos de vista.

• Swiss Army Knife


É uma classe cuja interface é grande demais. O projetista tenta antecipar
na interface todos os possíves usos da classe no futuro

• Reinvent the Wheel


Nova biblioteca de parsing para XML
Anti Design Patterns
Gerenciais

• Analysis Paralysis
Analistas buscam o entendimento perfeito e completo do
problema

• Death by Planning
Excesso no planejamento do que se vai fazer

• Intellectual Violence
Utilização prepotente de um conhecimento sobre uma
determinada teoria, tecnologia ou jargão específico para intimidar
outras pessoas numa reunião

• Smoke and Mirrors (ou Vaporware)


Gerentes pedem para programadores criarem GUIs com a casca
de um sistema ainda não desenvolvido. O objetivo é mostrar a
potenciais clientes o que poderia ser feito. Gerentes VENDEM o
sistema que não foi desenvolvido
Design Patterns
Criacionais
Abstract factory Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.

Builder Separate the construction of a complex object from its


representation so that the same construction process can create
different representations.

Connection pool Avoid expensive multiple connect/disconnect operations.

Factory method Define an interface for creating an object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.

Lazy initialization Tactic of delaying the creation of an object, the calculation of a


value, or some other expensive process until the first time it is
needed.

Multiton Ensure a class has only named instances, and provide global point of
access to them.

Object pool Avoid expensive acquisition and release of resources by recycling


objects that are no longer in use

Prototype Specify the kinds of objects to create using a prototypical instance,


and create new objects by copying this prototype.

Resource acquisition isEnsure


initialization
that resources are properly released by tying them to the
lifespan of suitable objects.

Singleton Ensure a class has only one instance, and provide a global point of
access to it.
Design Patterns
Estruturais
Adapter or Convert the interface of a class into another interface clients expect. Adapter
lets classes work together that couldn't otherwise because of incompatible
Wrapper interfaces.

Bridge Decouple an abstraction from its implementation so that the two can vary
independently.

Composite Compose objects into tree structures to represent part-whole hierarchies.


Composite lets clients treat individual objects and compositions of objects
uniformly.

Decorator Attach additional responsibilities to an object dynamically keeping the same


interface. Decorators provide a flexible alternative to subclassing for
extending functionality.

Facade Provide a unified interface to a set of interfaces in a subsystem. Facade


defines a higher-level interface that makes the subsystem easier to use.

Flyweight Use sharing to support large numbers of fine-grained objects efficiently.

Proxy Provide a surrogate or placeholder for another object to control access to it.
Design Patterns
Comportamentais
Blackboard Generalized observer, which allows multiple readers and writers. Communicates
information system-wide.
Chain of responsibility Avoid coupling the sender of a request to its receiver by giving more than one
object a chance to handle the request. Chain the receiving objects and pass the
request along the chain until an object handles it.
Command Encapsulate a request as an object, thereby letting you parameterize clients
with different requests, queue or log requests, and support undoable
operations.
Interpreter Given a language, define a representation for its grammar along with an
interpreter that uses the representation to interpret sentences in the language.
Iterator Provide a way to access the elements of an aggregate object sequentially
without exposing its underlying representation.
Mediator Define an object that encapsulates how a set of objects interact. Mediator
promotes loose coupling by keeping objects from referring to each other
explicitly, and it lets you vary their interaction independently.
Memento Without violating encapsulation, capture and externalize an object's internal
state so that the object can be restored to this state later.
Null Object Designed to act as a default value of an object.

Observer or Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.
Publish/subscribe
Restorer An alternative to the existing Memento pattern.

Specification Recombinable business logic in a boolean fashion

State Allow an object to alter its behavior when its internal state changes. The object
will appear to change its class.
Strategy Define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from clients
that use it.
Template method Define the skeleton of an algorithm in an operation, deferring some steps to
subclasses. Template Method lets subclasses redefine certain steps of an
algorithm without changing the algorithm's structure.
Visitor Represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the
elements on which it operates.
Bridge
• Motivação
– Abstração com diferentes implementações
– Tanto a abstração quanto as implementações podem evoluir

• Cenários
– Camada de persistência
– Consultas em bases heterogêneas
– Renderização de GUI

• Objetivo
– Desacoplar a abstração da suas implementações
Bridge

Abstraction:
Interface da abstração. Algumas literaturas mostram a interface com a
referência ao Implementor.

AbstractionImpl:
A implementação da abstração na qual referencia e invoca o
implementador

Implementor:
A interface para a implementação. Nem sempre corresponde a interface
Abstraction.

ConcreteImplementor N:
Bridge
Camada de Persistência
Bridge
QueryManager
Observer
• Motivação
– Manter estado consistente entre os módulos do sistema
– Refletir mudança de estado em módulos do sistema

• Cenários
– MVC
– Gerência de eventos (GUI)
– ...

• Objetivo
– Reduzir o acoplamento e as dependências nas mudanças de
estados
– Permitir que no futuro mais módulos possam ser adicionados ou
removidos garantindo a consistência de estado
– Permitir a mudança de estado de objetos desconhecidos
Observer

Subject:
Classe que é observada e conhece seus “observadores”.
Deve fornecer uma interface para anexar e desanexar os seus “observadores” .

Observer :
Define a interface de mudança de estado para os objetos que devem ser notificados
da mudança de estado no subject.

ConcreteSubject :
Implementação do subject que possui os estados para os objetos de ConcreteObserver
Envia a notificação para todos os seus observadores quando ocorre uma mudança de seu estado.

ConcreteObserver:
Mantém uma referência para o ConcreteSubject para reconhecer a mudança de estado.
Dependendo da interface (parâmetros da notificação), não precisa ter referência para o Subject.

You might also like