FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Laboratório de
Desenvolvimento de Software
FEUP/MIEIC, 2010/11
Nuno Flores
nuno.flores at fe.up.pt
Rosaldo Rossetti
rossetti at fe.up.pt
Filipe Correia
filipe.correia at fe.up.pt
http://paginas.fe.up.pt/~nflores/dokuwiki/doku.php?id=teaching:1011:ldso
Arquitectar...
!
Arquitectar uma pequena cabana parece-nos fácil...
janela
porta
parede
telhado
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Arquitectar...
!
Uma pequena “cabana de software” conhecida...
!
Que elementos identificam aqui?
Arquitectar...
!
Menos fácil será arquitectar uma casa...
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Arquitectar...
!
Ou um prédio de 6 andares...
Como dispor e ligar as várias habitações?
Arquitectar...
!
Ou um arranha-céus de 88 pisos e 452 metros de altura...
37,000 toneladas de ferro
90 seg das caves ao topo
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Arquitectar...
!
Quais as principais diferenças entre estas construções?
• Dimensões
• Custos
• Prazos
• Processo
• Competências e equipas
• Materiais e tecnologias
• Riscos associados
• Robustez
• Longevidade...
Engenharias tradicionais
!
Nas engenharias tradicionais existem “sistemas estáveis”,
maduros, de referência
• Exemplos: edifícios, aviões, automóveis, barcos, pontes, etc.
!
Os “sistemas estáveis” evoluíram ao longo do tempo
• Por tentativa-e-erro
• Por constante adaptação a necessidades específicas
• Por reutilização e refinamento de soluções comprovadamente boas
• Por diversos avanços nos materiais e processos usados e na sua
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Engenharia de Software: mais dificil?
!
Invisibilidade das construções (produto lógico)
!
Natureza temporal complexa de compreender (discreto)
!
Grandes necessidades de evolução ao longo da sua vida
!
Têm que ser facilmente adaptáveis; cada caso é único
!
Evolução rápida das tecnologias subjacentes
!
Passado bem mais curto
!
Não obedecem a leis físicas da natureza
Desenho de Software: níveis principais
Arquitectura
Código-fonte
Executável
módulos
interligações
algoritmos
estruturas de dados
pilhas de rotinas
alocação de registos
código-máquina
Que módulos?
Como os interligar?
Que gestão de memória?
Que instruções utilizar?
Que estruturas de dados?
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Arquitectura de Software
!
A arquitectura de software compreende o conjunto de
decisões significativas acerca da organização de um
sistema de software
• Que elementos estruturais e interfaces compõem o sistema?
• Quais os mecanismos para composição dos elementos estruturais?
• Quais os comportamentos de colaboração entre os elementos?
• Qual o estilo de arquitectura geral do sistema?
módulos
interfaces
conectores
Arquitectura de Software
!
O papel da arquitectura é o mesmo
• Controlar complexidade do sistema (tecnológica e de escala)
• Garantir a integridade do sistema
• Garantir os atributos de qualidade do sistema
- Escalabilidade, Interoperabilidade, usabilidade, desempenho,
adaptabilidade, custo, prazos, modularidade, etc.
• Melhorar a previsibilidade do desenvolvimento
• Equilibrar forças e estabelecer compromissos que influenciam o
desenvolvimento do sistema e a sua evolução futura
• Facilitar a cooperação de equipas de desenvolvimento
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Estilos de Arquitectura
!
Pipes & Filters
• Exemplo: comandos do sistema operativo Unix
!
Object-orientation
• Exemplo: quase tudo
!
Event-based
• Exemplo: interfaces gráficas
!
Layered Systems
• Exemplo: aplicações empresariais para a web
!
Repositories
• Exemplo: sistemas de informação e bases de dados
!
Interpreters
• Exemplo: compiladores, shell de comandos
!
Process Control
• Exemplo: sistemas distribuídos (RPC, DCE, Web Services, ...)
Graphical
User
Interface
Business
Object
Model
Relational
Database
Padrões de Software
Abstract Factory, Builder, Singleton,
Factory Method, Prototype, Adapter,
Bridge, Composite, Decorator, Proxy,
Chain of Responsability, Command,
Flyweight, Interpreter, Iterator,
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Frameworks Orientadas por Objectos
!
As frameworks são uma poderosa técnica de reutilização
de software que permitem reutilização de código e
desenho.
!
Frameworks + componentes + padrões
• tecnologia actualmente existente mais capaz de suportar
reutilização de software em larga-escala.
Application 1
Application 2
Application
3
Application
Code 2
Application
Code 3
Framework
code
Application
Code 1
abstraction
Callbacks
Hooks
Plugins
...
Framework
code
Exemplo: JUnit
!
Framework para testes unitários
• JUnit é uma framework open source em Java para testes unitários
utilizada para escrever e executar testes repetitivos.
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Patterns of Software
Cristopher Alexander
!
The concept of “patterns” has its origins on the work of
Cristopher Alexander.
!
For about 10 years, Alexander has captured and documented
generic solutions for recurring problems in the domain of civil
architecture.
!
The initial goal was to enable non-experts to architect and design
their own houses and communities.
!
This work resulted on several books:
• “A Pattern Language”
• “The Timeless Way of Building”
• “The Oregon Experiment”
• ...
• “The Nature of Order”, vol. I, II, III, IV.
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
“A Pattern Language”
[Alexander77]
!
253 patterns
• The book presnets several Alexander patterns, i.e., textual
descriptions of solutions to recurrent problems of civil architecture.
!
Pattern definition, by Alexander
“Each pattern describes a problem that occur over and over again in our
environment and then describes the core of the solution to that problem in
such a way that you can use this solution a million times over without ever
doing it the same way twice” [Alexander77, p. x]
!
Shorter definition
• Patterns are a textual description of a generic solution for a
recurrent problem in a specific context.
“A Pattern Language”: examples
!
253 patterns: from global to particular
• In “A Pattern Language” are described 253 patterns, interrelated,
varying on the level of detail, starting from the global to particular.
!
Some examples:
• 1. Independent Regions
• 2. The Distribution of Towns
• 16. Web of Public Transportation
• 83. Master and Apprentices
• 134. Zen View
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
“83. Master and Apprentices”
!
Problem
“The fundamental learning situation is one in which a person learns by
helping someone who really knows what he is doing.” [Alexander77, p. 413]
!
Solutions
“Arrange the work in every workgroup, industry, and office, in such a way
that work and learning go forward hand in hand. Treat every peace of work
as an opportunity for learning. To this end, organize work around a tradition
of masters and apprentices: and support this form of social organization
with a division of the workspace into spacial clusters - one for each master
and his apprentices - where they can work and meet
together.” [Alexander77, p. 1159]
“251. Different Chairs”
!
Problem
“People are different sizes: they sit in different ways. And yet there is a
tendency in modern times to make all chairs alike.” [Alexander77, p. 1158]
!
Solution
“Never furnish any place with chairs that are identically the same. Choose a
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Form of Alexander Patterns
Name
One sentence or descriptive name identifying the pattern
Example
Photos, drawings, descriptions illustrating pattern
applications.
Context
When to apply the pattern? Why the pattern exists and how
general is it.
Problem
Describe the relevant forces and restrictions and how they
interact.
Solution
Relations and dynamic rules that describe how to build the
artefacts in accordance to the pattern.
Similar and variant patterns are described. Also other
patterns relevant to the use of this pattern.
POSA Patterns
“Pattern Oriented Software Architecture”
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Pattern Oriented Software Architecture
A System of Patterns, Buschmann et al, 1996
!
A book about patterns for software architecture.
!
A book to support both novices and experts in software
development.
!
It should support experts In the design of large-scale and
complex software systems with defined properties.
!
It should also enable them to learn from the experience of
other experts.
Architectural Patterns
!
Definition (Buschmann et al)
• An architectural pattern expresses a fundamental structural
organization schema for software systems. It provides a set of
predefined subsystems, specifies their responsibilities, and includes
rules and guidelines for organizing the relationships between them.
!
Architectural templates
• Architectural patterns are templates for concrete software
architectures.
• They specify the system-wide structural properties of an application,
and have an impact on the architecture of its subsystems.
!
Fundamental design decisions
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Four Categories of Architectural Patterns
!
From Mud to Structure
• To help avoiding a 'sea' of components or objects by supporting a controlled
decomposition of a task into cooperating subtasks.
• Patterns: Layers (31), Pipes and Filters (53), Blackboard (71).
!
Distributed Systems
• To help on architecting distributed systems.
• Patterns: Broker (99); refers to Microkernel (171), Pipes and Filters (53).
!
Interactive Systems
• To support the structuring of software systems that feature HCI.
• Patterns: Model-View-Controller (125), Presentation-Abstraction-Control
pattern (145).
!
Adaptable Systems
• To support extension of applications and their adaptation to evolving
technology and changing functional requirements.
• Patterns: Reflection (193), Microkernel (171).
Design Patterns
!
Definition (Gamma et al.)
• A design pattern provides a scheme for refining the subsystems or
components of a software system, or the relationships between
them. It describes a commonly-recurring structure of
communicating components that solves a general design problem
within a particular context.
!
Design patterns are medium-scale patterns
• Smaller in scale than architectural patterns
• Tend to be independent of a particular programming language or
programming paradigm.
• The application of a design pattern has no effect on the
fundamental structure of a software system, but may have a strong
influence on the architecture of a subsystem.
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Categories of Design Patterns
!
Structural Decomposition
• To support a suitable decomposition of subsystems and complex
components into cooperating parts.
• Patterns: Whole-Part (225)
!
Organization of Work
• To define how components collaborate together to solve a complex problem.
• Patterns: Master-Slave (245)
!
Access Control
• To guard and control access to services or components.
• Patterns: Proxy (263).
!
Management
• To handle homogenous collections of objects, services and components in
their entirety.
• Patterns: Command Processor (277), View Handler (291).
!
Communication
• To organize communication between components.
• Patterns: Forwarder-Receiver (307), Client Dispatcher-Server (323),
Publisher-Subscriber (339).
Pattern form
!
Name The name and a short summary of the pattern.
!
Also Known As Other names for the pattern, if any are known.
!
Example A real-world example demonstrating the problem and the pattern’s need.
!
Context The situations in which the pattern may apply
!
Problem The problem the pattern addresses, including a discussion of its forces.
!
Solution The fundamental solution principle underlying the pattern.
!
Structure A detailed specification of the structural aspects of the pattern.
!
Dynamics Typical scenarios describing the run-time behavior of the pattern.
!
Implementation Guidelines or suggestions for implementing the pattern.
!
Example Resolved Discussion of any important aspects for resolving the example.
!
Variants A brief description of variants or specializations of a pattern.
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Basic and Simple Patterns first
!
Simple patterns are easy to understand and appear in
many well-structured software systems.
!
Architectural patterns
• Layers (31)
• Pipes and Filters (53)
!
Design patterns
• Proxy (263)
• Forwarder-Receiver (307)
Abstract Factory, Builder, Singleton,
Factory Method, Prototype, Adapter,
Bridge, Composite, Decorator,
Facade, Flyweight, Proxy, Chain of
Responsability, Command,
Interpreter, Iterator, Mediator,
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
GoF Design Patterns
(GoF = Gang-of-Four)
“GoF Patterns”
!
23 padrões que variam em nível de abstracção e
granularidade
!
São de três tipos, de acordo com o objectivo:
• Creational
- auxiliam no projecto de sistemas flexíveis quanto à forma como os
objectos são criados, compostos e representados
• Structural
- incidem sobre como as classes e objectos se compõem por forma a
constituírem estruturas maiores e mais complexas
• Behavioral
- incidem sobre os algoritmos e a atribuição de responsabilidades
- descrevem não só padrões de objectos e classes mas também padrões
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Nomes dos “GoF Patterns”
Creational
Abstract Factory
Builder
Factory Method
Prototype
Singleton
Structural
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
• Proxy
Behavioral
Chain of Responsability
Command
Interpreter
• Iterator
Mediator
Memento
• Observer
State
Strategy
Template Method
Visitor
Creational Patterns
Design Pattern
Aspecto(s) que pode(m) variar
Abstract Factory
(87)
familias de objectos produto
Builder (97)
forma de criação de objectos
compostos
Factory Method
(107)
subclasse do objecto que é criado
Prototype (117)
classe do objecto que é instanciado
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Structural Patterns
Design Pattern
Aspecto(s) que pode(m) variar
Adapter (139)
interface para um objecto
Bridge (151)
Implementação de um objecto
Composite (163)
estrutura e composição de um objecto
Decorator (175)
responsabilidades de um objecto sem
subclassing
Facade (185)
interface para um subsistema
Flyweight (195)
custo de armazenamento de objecto
Proxy (207)
forma de acesso a um objecto; a sua
localização
Behavioral Patterns
Design Pattern
Aspecto(s) que pode(m) variar
Chain of Responsibility
(223)
objecto que pode responder a um pedido
Command (233)
quando e como um pedido pode ser respondido
Interpreter (243)
gramática e interpretação de uma linguagem
Iterator (257)
forma de aceder e percorrer os elementos de um
objecto agregado (multi-valor)
Mediator (273)
como e que objectos interactuam entre si
Memento (283)
que informação privada é armazenada fora de um
objecto, e quando
Observer (293)
número de objectos que dependem de outro objecto;
como os objectos dependentes se mantêm
actualizados
State (305)
estados de um objecto
Strategy (315)
um algoritmo
Template Method (325)
passos de um algoritmo
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011
Uma ordem de aprendizagem
!
Template Method
!
Factory Method
!
Strategy
!
Decorator
!
Composite
!
Iterator
!
Abstract Factory
!
Builder
!
Singleton
!
Proxy
!
Adapter
!
Bridge
!
Mediator
!
Observer
!
Chain of Responsibility
!
Memento
!
Command
!
Prototype
!
State
!
Visitor
!
Flyweight
!
Interpreter
!
Façade
Comentários
!
Os “GoF Design Patterns” auxiliam no projecto de sistemas
de software reutilizáveis e facilmente extensíveis, embora
à custa de um aumento da sofisticação dos modelos de
classes e das suas interacções.
!
Estes padrões aplicam-se a inúmeros domínios de
problemas: editores de desenho, banca,
telecomunicações, CAD, CASE’s, aplicações médicas, etc.
!
Muitos destes padrões são considerados padrões
atómicos, isto é, são padrões que não encerram em si
outros padrões.
FEUP/MIEIC ! Ademar Aguiar ! Nuno Flores ! Laboratório de Desenvolvimento de Software ! 2010/2011