10 - design patterns - part1
DESCRIPTION
Creational PatternsStructural PatternsTRANSCRIPT
-
Copyright IBM Corporation 2013
IBM GDC EE
Introduc)on to
OO Design Pa3erns
Victor Rentea
December 9 & 16, 2013
Part 1 Object-Oriented Programming Course "Politehnica" University of Bucharest
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
IntroducEon Principles of Good OO Design CreaEonal PaJerns Structural PaJerns Behavioral PaJerns AnE-paJerns
Contents
Agenda
2
Part I
Part II
Test
Test
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
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
Introduction to OO Design
Two Basic Concepts
3
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=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
Introduction to OO Design
Design Pa3erns ? What & Why ?
4
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
Introduction to OO Design
GoF
5
Image from Head First Design PaJerns ISBN: 978-0-596-00712-6
(Swiss, IBM)
(USA)
(USA, IBM)
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
IntroducEon Principles of Good OO Design CreaEonal PaJerns Structural PaJerns Test
Contents Part 1
Agenda
6
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
Acer all, the code actually works The design is bad when it doesnt stand
CHANGE
Design for change
Introduction to OO Design
But what is bad design ?
7
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=pull out and isolate changing parts of your system
Contain impact of changes - Leave working code unaected
" Tax computaEons, external services, visual
Principles of Good OO Design
Encapsulate What Varies
8
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=depend on abstrac*ons rather than implementa*ons
Interfaces tend to be more stable Enjoy alternaEve implementaEons
" List, Map or File
Principles of Good OO Design
Program to Abstrac)ons
9
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
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
Principles of Good OO Design
Favor Composi)on over Inheritance
10
OtherClass
MyClass OtherClass
MyClass
+reference
depends on your applicaEon domain
" class Duck { private Fly y; private Quack quack; }
" class DuckThatQuaksAndFlies extends Quacking, Flying
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
Single Responsibility = 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 = decouple high-level modules from low-level components
Principles of Good OO Design
SOLID Principles
11
~high Cohesion
your domain logic
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
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 - At extreme: only when it is absolutely necessary YAGNI [eXtreme Programming]
Principles of Good OO Design
Overengineering PiWall
12
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
AbstracEons Simplicity (defense against CHANGE)
Principles of Good OO Design
Designing is a Tradeo
13
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
IntroducEon Principles of Good OO Design Crea)onal Pa3erns Structural PaJerns Test
Contents Part 1
Agenda
14
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=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
Creational Patterns
Singleton
15 " MulEthreading + Lazy init Singleton
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();
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
Customer customer = new Customer(); customer.setName("John Doe");
List labels = new ArrayList();
labels.add("Label1");
customer.setLabels(labels);
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
public class CustomerBuilder { private Customer customer=new Customer();
public Builder withName(String name) { customer.setName(name);
return this; }
public Builder withLabel(String label) {
customer.getLabels().add(label);
return this; }
... public Customer build() {
return customer; }
}
public class Customer { private String name; ...
public static class Builder { private Customer customer=new Customer();
public Builder withName(String name) { customer.setName(name);
return this; }
public Builder withLabel(String label) {
customer.getLabels().add(label);
return this;
}
... public Customer build() {
return customer; }
}
}
Creational Patterns
Fluent Builder
16 " .build() can validate the instance
Customer customer = new Customer.Builder() .withName("John Doe")
.withLabel("Label1")
.withAddress(new Address.Builder()
.withStreetName("Viorele")
.build()) .build();
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
ConcreteProduct1A ConcreteProduct1A
=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#
ConcreteFactory3
+createProductA() +createProductB()
ConcreteFactory2
+createProductA() +createProductB()
Creational Patterns
Abstract Factory
17
interface AbstractFactory
+createProductA() +createProductB()
interface ProductA
ConcreteFactory1
+createProductA() +createProductB()
ConcreteProduct1A creates return new ConcreteProduct1A();
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
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
Creational Patterns
Summary
18
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
IntroducEon Principles of Good OO Design CreaEonal PaJerns Structural Pa3erns Test & ExplanaEons
Contents Part 1
Agenda
19
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=convert the interface of an external class into another interface the code expects
AnE-CorrupEon Layer - Decouple from external contracts
@Override public String operation(Date date) { String s = // format date as string
int result = adaptee.externalOperation(s); String adaptedResult = // adapt result
return adaptedResult; }
Structural Patterns
Adapter
20
Wrapper
interface AdaptedContract
+opera:on()
Adapter
-adaptee
+operaEon()
ExternalClass
+externalOperaEon() delegate
/subsystem
public int externalOperation(String dateStr)
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=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
Structural Patterns
Proxy
21
interface Subject
+request()
RealSubject
+request()
Proxy
+request()
represents
Can be created at run-Eme with java.lang.reflect.Proxy
delegate HTTP
actually uses
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
=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
Structural Patterns
Decorator
22
interface Subject
+request()
RealSubject
+request()
Proxy
+request()
actually uses
Decorator
-delegate
+request() delegate
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
Adapter Proxy Decorator
Purpose Adapt an interface/contract
Intermediate interactions
Attach responsibilities
Implemented Interface
Client-needed Invoked Object (Subject)
Invoked Object (Subject)
Remote capable (local call) (local call)
Overloaded Semantics
Anti-Corruption Dynamic Proxy
Structural Patterns
Whats the dierence ?
23
Execute code before/after/instead of the actual call ~ AOP
-
24
-
Cnd vreau s , folosesc , iar n cod
Singleton
Fluent Builder
Factory
Adapter
Proxy
Decorator
Program to Abstrac)ons
compoziie, nu motenire
Single Responsibility
Interface Segrega)on
denesc o metod abstract createChair():Chair (Chair e o interfa) 2
scriu clase care se modic dintr-un singur moEv 7
expun metode care transform apelurile i le deleg instanei int ncapsulate. 4
i marchez constructorul ca private i stochez instana unic ntr-un cmp static 9
Method Chaining: metode care seteaz cmpuri i ntorc mereu this 1
mi protejez codul de schimbri n implem. sau s pot alege implementarea la run-Eme g
decuplez creerea unei familii de obiecte i
convertesc o interfa la alta, sau m izolez de un sistem extern a
adaug responsabilitate pe anumite apeluri de metode j
creez i populez un obiect ntr-un mod uor de neles d
folosesc comportamente sau stare dintr-o alt clas ntr-un mod exibil c
proiectez componente uor de neles i de refolosit h
decuplez logica aplicaiei (domain logic) de detalii mrunte de implementare e
permit cel mult o instan dintr-o clas b
intermediez interaciunile cu un obiect (de exemplu, trimind apelurile peste HTTP) f
dau clientului o instan surogat (nlocuitor) ce implementeaz interfaa obiectului de apelat 10
ncerc s depind doar de interfee sau clase abstracte, nu de implementri concrete 8
ncapsulez obiectul int, implementez interfaa lui delegnd apelurile la instana ncapsulat. 6
n loc s extends acea alt clas, in o referin la o instan a ei ntr-un cmp membru 3
creez interfete dedicate pentru clieni, care le ofer acestora exact ce au cerut (nimic n plus) 5
j 6
Dependency Inversion
expun interfee concise, stabile i simplu de uElizat de clienii mei k
n clasele de domain logic evit s depind direct de clase de infrastructur, e.g. HTTP, DB, XML, HTML 11
13 minute
-
creez interfete dedicate pentru clieni, care le ofer acestora exact ce au cerut (nimic n plus) 5
scriu clase care se modic dintr-un singur moEv 7
i marchez constructorul ca private i stochez instana unic ntr-un cmp static 9
Method Chaining: metode care seteaz cmpuri i ntorc mereu this 1
denesc o metod abstract createChair():Chair (Chair e o interfa) 2
expun metode care transform apelurile i le deleg instanei int ncapsulate. 4
dau clientului o instan surogat (nlocuitor) ce implementeaz interfaa obiectului de apelat 10
n loc s extends acea alt clas, in o referin la o instan a ei ntr-un cmp membru 3
ncerc s depind doar de interfee sau clase abstracte, nu de implementri concrete 8
ncapsulez obiectul int, implementez interfaa lui delegnd apelurile la instana ncapsulat. 6
Singleton
Fluent Builder
Factory
Adapter
Proxy
Decorator
Program to Abstrac)ons
compoziie, nu motenire
Single Responsibility
Interface Segrega)on
permit cel mult o instan dintr-o clas b
creez i populez un obiect ntr-un mod uor de neles d
decuplez creerea unei familii de obiecte i
convertesc o interfa la alta, sau m izolez de un sistem extern a
intermediez interaciunile cu un obiect (de exemplu, trimind apelurile peste HTTP) f
adaug responsabilitate pe anumite apeluri de metode j
mi protejez codul de schimbri n implem. sau s pot alege implementarea la run-Eme g
folosesc comportamente sau stare dintr-o alt clas ntr-un mod exibil c
proiectez componente uor de neles i de refolosit h
expun interfee concise, stabile i simplu de uElizat de clienii mei k
Cnd vreau s , folosesc , iar n cod
n clasele de domain logic evit s depind direct de clase de infrastructur, e.g. HTTP, DB, XML, HTML 11
Dependency Inversion
decuplez logica aplicaiei (domain logic) de detalii mrunte de implementare e
-
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
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
Introduc)on Principles of Good OO Design Crea)onal Pa3erns Structural Pa3erns Behavioral PaJerns AnE-paJerns
What we covered
Summary
28
Part II
Part I
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
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
Want to dig more ?
References
29
-
Copyright IBM Corporation 2013 OO Design Patterns | December 2013 @ UPB
EJB 3 JPA Spring Java EE Design PaJer. Java EE6 XML, XSD & JAXB RESTful WS
SOAP WS Servlets & JSP HTML5/CSS3 Mobile Apps JSF and many more
R4