Sunteți pe pagina 1din 30

IBM GDC EE

Introduc)on to

OO Design Pa3erns
Victor Rentea
December 9 & 16, 2013

Object-Oriented Programming Course
"Politehnica" University of Bucharest

Part 1
Copyright IBM Corporation 2013

Contents

Part II

Part I

Agenda

IntroducEon
Principles of Good OO Design
CreaEonal PaJerns
Structural PaJerns
Behavioral PaJerns
AnE-paJerns

OO Design Patterns | December 2013 @ UPB

Test
Test

Copyright IBM Corporation 2013

Introduction to OO Design

Two Basic Concepts


Cohesion
= the degree to which the elements of a component belong together
- High Cohesion: simple and reusable code

Coupling
= the degree to which components depend on each other
- Loose Coupling: changes dont ripple throughout the code

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Introduction to OO Design

Design Pa3erns ? What & Why ?


=common solu*on to a recurring problem

Shared Vocabulary
-

Talk less, understand beJer

Understand ExisEng Code


-

ExisEng applicaEons or Frameworks

Produce Quality Code


-

Apply proven soluEons to classic problems


OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Introduction to OO Design

GoF

(USA)

(USA, IBM)

(Swiss, IBM)

Image from Head First Design PaJerns ISBN: 978-0-596-00712-6

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Contents Part 1

Agenda
IntroducEon
Principles of Good OO Design
CreaEonal PaJerns
Structural PaJerns
Test

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Introduction to OO Design

But what is bad design ?


Acer all, the code actually works
The design is bad when it doesnt stand

CHANGE
Design for change
7

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Principles of Good OO Design

Encapsulate What Varies


=pull out and isolate changing parts of your system

Contain impact of changes


-

Leave working code unaected

" Tax computaEons, external services, visual


8

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Principles of Good OO Design

Program to Abstrac)ons
=depend on abstrac*ons rather than implementa*ons

Interfaces tend to be more stable


Enjoy alternaEve implementaEons

" List, Map or File


9

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Principles of Good OO Design

OtherClass

MyClass

Favor +reference
Composi)on
over Inheritance
OtherClass

MyClass

" class Duck { private Fly y;

private Quack quack; }

" class DuckThatQuaksAndFlies

extends Quacking, Flying

to use behavior or state from another class


Avoid class explosion
-

No mulEple extends

Behaviors can be switched dynamically


Extend only when is-a holds
Manager is-a Employee
- Employee is-a CallableByPhone
-

10

OO Design Patterns | December 2013 @ UPB

depends on your applicaEon domain


Copyright IBM Corporation 2013

Principles of Good OO Design

SOLID Principles
Single Responsibility

~high Cohesion

= a class should have only 1 single responsibility (reason to change)

Open/Closed
= lower the impact of adding new funcEonality on exisEng code

Liskov SubsEtuEon
Interface SegregaEon
= keep interfaces as minimal as possible (dont tell if not asked)

Dependency Inversion
domain
logic from low-level components
= decouple hyour
igh-level
modules
11

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Principles of Good OO Design

Overengineering PiWall
When to decouple varying parts of the system ?
Premature Encapsula)on is the Root of all Evil
Adam Bien

Upfront
-

where changes will most certainly occur

Later on
-

12

At extreme: only when it is absolutely necessary YAGNI [eXtreme Programming]

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Principles of Good OO Design

Designing is a Tradeo

AbstracEons

Simplicity

(defense against CHANGE)

13

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Contents Part 1

Agenda
IntroducEon
Principles of Good OO Design
Crea)onal Pa3erns
Structural PaJerns
Test

14

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Creational Patterns

Singleton
=have only one instance of a class in your applica*on,

which is stored in a static eld


Used to share data
Closed Code
Hard to replace, e.g. for tesEng
- Boilerplate
-

AlternaEve:
-

Container manages instance lifecycle

public class Singleton {


private static Singleton INSTANCE;

private Singleton() { /*initialization*/ }

public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
private String myIP;
}
Singleton s = Singleton.getInstance();

15

OO Design Patterns | December 2013 @ UPB

" MulEthreading + Lazy init Singleton

Copyright IBM Corporation 2013

Creational Patterns

Fluent Builder
public class Customer {
private String name;
...
public class CustomerBuilder {
public static class Builder {
private Customer customer=new Customer();
private Customer customer=new Customer();

public Builder withName(String name) {
customer.setName(name);
return this;
}
public Builder withLabel(String label) {
Customer customer = new Customer();
customer.getLabels().add(label);
customer.setName("John Doe");
return this;
List<String> labels = new ArrayList<>();
}
...
labels.add("Label1");
public Customer build() {
customer.setLabels(labels);
return customer;
Address address = new Address();
}
adress.setStreetName("Viorele");
}
customer.setAddress(address);

}

=create an instance in a human readable way


No (useless) auxiliary variables
- Based on Method Chaining:
(every with() method returns this)
-

Best as inner class


Customer customer = new Customer.Builder()
.withName("John Doe")
.withLabel("Label1")
.withAddress(new Address.Builder()
.withStreetName("Viorele")
.build())
.build();

16

OO Design Patterns | December 2013 @ UPB

" .build() can validate the instance

Copyright IBM Corporation 2013

Creational Patterns

Abstract Factory
=dene an interface for crea*ng families of objects but
let Factorys realiza*ons choose the realiza*ons to instan*ate
-

Examples: XML DOMJSE, JMSJEE, DbProviderFactory#


interface
AbstractFactory

interface
ProductA

+createProductA()
+createProductB()
ConcreteFactory1
ConcreteFactory2
ConcreteFactory3
+createProductA()
+createProductA()
+createProductA()
+createProductB()
+createProductB()
+createProductB()

return new
ConcreteProduct1A();

17

OO Design Patterns | December 2013 @ UPB

creates

ConcreteProduct1A
ConcreteProduct1A
ConcreteProduct1A

Copyright IBM Corporation 2013

Creational Patterns

Summary
Singleton
Guarantees at most 1 instance of a class per applicaEon
- by which you can share data throughout the enEre applicaEon
-

Fluent Builder
-

Lets you create instances in an easily readable way

Abstract Factory
Lets you create families of related objects,
- that can then work together
-

18

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Contents Part 1

Agenda
IntroducEon
Principles of Good OO Design
CreaEonal PaJerns
Structural Pa3erns
Test & ExplanaEons

19

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Structural Patterns

Wrapper

Adapter

=convert the interface of an external class /subsystem


into another interface the code expects

AnE-CorrupEon Layer
-

Decouple from external contracts


interface
AdaptedContract

+opera:on()

@Override
public String operation(Date date) {
String s = // format date as string
int result = adaptee.externalOperation(s);
String adaptedResult = // adapt result
return adaptedResult;
}
public int externalOperation(String dateStr)

Adapter

-adaptee

+operaEon()
20

OO Design Patterns | December 2013 @ UPB

ExternalClass

delegate

+externalOperaEon()
Copyright IBM Corporation 2013

Structural Patterns

Proxy
=placeholder intermedia*ng interac*ons with an object
Remote invocaEons (e.g. web service client proxy/stub)
- AOP uses it for cross-cuzng concerns like Access Control, TransacEons, etc
In containers like EJB or Spring, injected references are Dynamic Proxy
-

interface
Subject

+request()

actually
uses
Can be created at run-Eme with
java.lang.reflect.Proxy
Proxy

+request()

21

OO Design Patterns | December 2013 @ UPB

represents

RealSubject

delegate
HTTP

+request()

Copyright IBM Corporation 2013

Structural Patterns

Decorator
=aAach addi*onal responsibili*es to objects methods
-

Implement the subjects interface,


in the methods, execute custom logic
before and acer delegaEng to the real (wrapped) instance

Proxy

interface
Subject

+request()

actually
uses

Decorator

-delegate

Proxy

+request()

+request()

22

RealSubject

OO Design Patterns | December 2013 @ UPB

delegate

+request()

Copyright IBM Corporation 2013

Structural Patterns

Whats the dierence ?


Adapter
Purpose

Adapt an
interface/contract

Proxy
Intermediate
interactions

Decorator
Attach
responsibilities

Execute code before/after/instead


of the actual call ~ AOP
Implemented
Interface
Remote capable
Overloaded
Semantics

23

Client-needed

Invoked Object
(Subject)

(local call)
Anti-Corruption

OO Design Patterns | December 2013 @ UPB

Invoked Object
(Subject)
(local call)

Dynamic Proxy

Copyright IBM Corporation 2013

24

Cnd vreau s

, folosesc

, iar n cod

13 minute

convertesc o interfa la alta, sau


m izolez de un sistem extern

Singleton

permit cel mult o instan dintr-o clas

Fluent
Builder

folosesc comportamente sau stare


dintr-o alt clas ntr-un mod exibil

Factory

3 la o instan a ei ntr-un cmp membru

creez i populez un obiect


ntr-un mod uor de neles

Adapter

4 le deleg instanei int ncapsulate.

decuplez logica aplicaiei (domain logic)


de detalii mrunte de implementare

Proxy

5 acestora exact ce au cerut (nimic n plus)

Method Chaining: metode care seteaz cmpuri

1 i ntorc mereu this

denesc o metod abstract createChair():Chair

2 (Chair e o interfa)

n loc s extends acea alt clas, in o referin


expun metode care transform apelurile i
creez interfete dedicate pentru clieni, care le ofer

intermediez interaciunile cu un obiect


f
(de exemplu, trimind apelurile peste HTTP)

j Decorator 6

obiectul int, implementez interfaa lui


6 ncapsulez
delegnd apelurile la instana ncapsulat.

mi protejez codul de schimbri n implem.


g
sau s pot alege implementarea la run-Eme

Program to
Abstrac)ons

7 scriu clase care se modic dintr-un singur moEv

proiectez componente uor de neles


i de refolosit

compoziie,
nu motenire

8 clase abstracte, nu de implementri concrete

decuplez creerea unei familii de obiecte

Single
Responsibility

9 stochez instana unic ntr-un cmp static

adaug responsabilitate pe anumite apeluri


de metode

Interface
Segrega)on

10 ce implementeaz interfaa obiectului de apelat

expun interfee concise, stabile i


simplu de uElizat de clienii mei

Dependency
Inversion

11 clase de infrastructur, e.g. HTTP, DB, XML, HTML

ncerc s depind doar de interfee sau


i marchez constructorul ca private i

dau clientului o instan surogat (nlocuitor)

n clasele de domain logic evit s depind direct de

Cnd vreau s

, folosesc , iar n cod

permit cel mult o instan dintr-o clas

marchez constructorul ca private i


b Singleton 9 i stochez
instana unic ntr-un cmp static

creez i populez un obiect


ntr-un mod uor de neles

Fluent
Builder

decuplez creerea unei familii de obiecte

Factory

convertesc o interfa la alta, sau


m izolez de un sistem extern

metode care transform apelurile i


a Adapter 4 expun
le deleg instanei int ncapsulate.

intermediez interaciunile cu un obiect


f
(de exemplu, trimind apelurile peste HTTP)
adaug responsabilitate pe anumite apeluri
de metode

Proxy

Method Chaining: metode care seteaz cmpuri

1 i ntorc mereu this

denesc o metod abstract createChair():Chair

2 (Chair e o interfa)

dau clientului o instan surogat (nlocuitor)

10 ce implementeaz interfaa obiectului de apelat

obiectul int, implementez interfaa lui


j Decorator 6 ncapsulez
delegnd apelurile la instana ncapsulat.

Program to
mi protejez codul de schimbri n implem.
g
Abstrac)ons
sau s pot alege implementarea la run-Eme
compoziie,
nu motenire

ncerc s depind doar de interfee sau

8 clase abstracte, nu de implementri concrete

folosesc comportamente sau stare


dintr-o alt clas ntr-un mod exibil

proiectez componente uor de neles


i de refolosit

Single
h Responsibility
7 scriu clase care se modic dintr-un singur moEv

expun interfee concise, stabile i


simplu de uElizat de clienii mei

Interface
Segrega)on

decuplez logica aplicaiei (domain logic)


de detalii mrunte de implementare

Dependency
Inversion

n loc s extends acea alt clas, in o referin

3 la o instan a ei ntr-un cmp membru

creez interfete dedicate pentru clieni, care le ofer

5 acestora exact ce au cerut (nimic n plus)

n clasele de domain logic evit s depind direct de

11 clase de infrastructur, e.g. HTTP, DB, XML, HTML

Cnd vreau s

, folosesc

, iar n cod

m izolez de un sistem extern, sau


s convertesc o interfa la alta

Adapter

ncapsulez obiectul int i metodele dorite transformnd


apelurile i delegndu-le instanei respecEve.

proiectez componente uor de nteles i de refolosit

Single Responsibility
Principle

scriu clase care se modic dintr-un singur moEv

adaug responsabilitate pe anumite apeluri de metode

Decorator

ncapsulez obiectul int i i implementez interfaa


delegnd apelurile la instana ncapsulat.

decuplez creerea unui obiect

Factory

denesc o metod abstract createChair():Chair,


(Chair e o interfa)

creez i populez un obiect ntr-un mod uor de neles

Fluent Builder

Method Chaining: metode care seteaz cmpuri i ntorc


mereu this

expun interfee ct mai stabile clienilor mei

Interface Segrega)on
Principle

creez interfete dedicate pentru clieni, care le ofer


acestora exact ce au cerut (nimic n plus)

folosesc comportamente sau stare dintr-o alt clas


ntr-un mod exibil

compoziie, nu
motenire

n loc s extends acea alt clas, in o referin la o


instan a ei ntr-un cmp membru

intermediez interaciunile cu un obiect


(de exemplu, trimind apelurile peste HTTP)

Proxy

dau clientului o instan surogat (nlocuitor) ce


implementeaz interfaa obiectului de apelat

mi protejez logica aplicaiei (domain logic) de detalii


mrunte de implementare

Dependency Inversion
Principle

evit s import n clasele de domain logic clase de


infrastructur, e.g. HTTP, DB, XML parsing, HTML

mi protejez codul de schimbri n implementare sau


vreau s pot alege implementarea la run-Eme

Program to
Abstrac)ons Principle

ncerc s depind doar de interfee sau clase abstracte, nu


de implementri concrete

What we covered

Part II

Part I

Summary

28

Introduc)on
Principles of Good OO Design
Crea)onal Pa3erns
Structural Pa3erns
Behavioral PaJerns
AnE-paJerns

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

Want to dig more ?

References
Head First: Design Pa3erns

Eric & Elisabeth Freeman, Kathy Sierra, Bert Bates, 2004


(all of it)

Design PaJerns: Elements of Reusable Object-Oriented Socware


Gang Of Four: E. Gamma, R. Helm, R. Johnson, J. Vlissides, 1995
(Applicability, Par:cipants and Consequences secEons)

PaJerns discussed: hJp://en.wikipedia.org/wiki/Design_PaJerns


(catalog at the boJom of the page)

SOLID Principles: hJp://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29


GRASP: hJp://en.wikipedia.org/wiki/GRASP_%28object-oriented_design%29
GoF Design PaJerns in Java SDK hJp://stackoverow.com/quesEons/1673841/examples-of-gof-design-paJerns
29

OO Design Patterns | December 2013 @ UPB

Copyright IBM Corporation 2013

EJB 3
JPA
Spring
Java EE Design PaJer.
Java EE6
XML, XSD & JAXB
RESTful WS
R4

OO Design Patterns | December 2013 @ UPB

SOAP WS
Servlets & JSP
HTML5/CSS3
Mobile Apps
JSF
and many more

Copyright IBM Corporation 2013

S-ar putea să vă placă și