To create better software we should be aware of existing well-proven software design solutions. Learn more about software patterns. The slides cover GRASP, architectural patterns, enterprise application patterns and GoF design patterns.
3. What is a Pattern!
!
A pattern is a general reusable solution to recurring
software design problem, arising in a specific context.!
Documents existing well-proven
design experience!
!
4. Pattern Consists of!
Context!
A situation giving a rise to a problem!
Problem!
The recurring problem arising in that context!
Solution!
A proven resolution of the problem!
!
C
P
S
5. Why Use Patterns!
• Specify abstractions above the level of single class!
• Create common vocabulary for communication!
• Provide means for documenting architectures!
• Assure support of defined properties!
• Help to manage software complexity!
• Allow to build complex software
9. What is GRASP!
General principles for assigning responsibility to
classes and objects in object-oriented design!
!
!
• Creator!
• Low Coupling!
• High Cohesion!
• Information Expert!
• Controller!
• Polymorphism!
• Indirection!
• Pure Fabrication!
• Protected Variations!
10. Creator!
Who should create a class A?!
Class B should create A if!
• B contains A
• B records A
• B closely uses A
• B has initializing data for A
For complex instantiation use Factory!
P
S
12. Low Coupling!
How to reduce the impact of changes?!
Assign the responsibility to maintain low coupling!
• Localized changes!
• Easier to understand!
• Easier to reuse!
P
S
14. High Cohesion!
How to keep classes focused and understandable?!
Assign the responsibility to maintain high cohesion!
• Easier to understand!
• Easier to reuse!
• Easier to maintain!
• Lower coupling!
!
P
S
16. Information Expert!
Whom to assign the responsibility for an operation?!
Assign the responsibility for an operation to the class
that has all necessary information to accomplish it!
• Better encapsulation!
• Higher cohesion!
P
S
18. Controller!
Who should handle events from UI?!
Assign the responsibility to the class representing use
case scenario !
[UseCase](Handler | Controller | Session)!
• Separate UI from application logic!
• Increase reusability!
P
S
20. Polymorphism!
How to handle different behavior based on type?!
Assign responsibilities for the behaviors with
polymorphic methods in types !
• Easier to extend (even without changing the clients)
P
S
22. Indirection!
How to avoid direct coupling between two classes?!
Assign the responsibility for the communication
between components to intermediate object!
• Lower coupling!
“All problems in computer science can be solved by another
level of indirection”!
David Wheeler!
P
S
24. Pure Fabrication!
!
Whom to assign the responsibility not violating low
coupling and high cohesion principles?!
Assign the responsibility to an artificial class not
belonging to domain!
• Lower coupling!
• Higher cohesion!
P
S
26. Protected Variations!
How to protect components from outside variations?!
Identify the points of variations and assign the
responsibility to ensure stable interface around them!
• Easier to extend!
• Lower coupling!
• Lower cost of changes!
P
S
27. Protected Variations Techniques!
• Data-Driven Design!
Reading metadata at runtime!
• Service Lookup !
Lookup up service class at runtime reading from configuration!
• Interpreter-Driven Design!
Support language and executing external scripts !
• Liskov Substitution Principle!
Interface implementers can be used interchangeably!
!
29. Structural Patterns!
• Layers!
UI, Services, Business Logic, Data Access!
• Pipes and Filters!
Chain of filters connected with pipes!
• Service-Oriented Architecture (SOA)!
Set of independent services!
• Microservices!
Set of small independently deployed services!
!
!
30. Layers!
A large system requiring decomposition!
How to organize work with low- and high-level issues?!
low-level: database, sensors, hardware !
high-level: user interface!
Divide system into appropriate amount of layers
placing them on top of each other!
Usage: Enterprise Applications, OS!
P
S
C
32. Pipes and Filters!
Processing data streams!
How to build flexible configurable system for
processing and transforming data streams?!
requirement: future enhancements!
Divide the task into sequential processing steps. The
output of each step is the input for the next.!
Usage: Workflow Processor, Compiler, UNIX Shell!
P
S
C
34. Service-Oriented Architecture!
A large system requiring high integrability!
How to build system architecture to provide high
integration capabilities and heterogeneous Uis?!
requirement: different clients (browser, mobile app, public API)!
Divide system into set of independent services
communicating by contract over network.!
Tech: Web Services, REST, WCF, Apache Thrift!
P
S
C
37. Model-View-Controller!
Interactive application with flexible user interface!
How to build a system with complex user interface
separated from core functionality!
requirement: easily-changeable UI!
Divide application into three areas: input (Model),
output (View) and processing (Controller)!
P
S
C
42. Microkernel!
Developing several applications, using the same core!
How to build an application platform requiring
continuous evolution and high-extensibility?!
!
Encapsulate core services in a microkernel, allowing
other components to communicate with each other!
P
S
C
44. Reflection!
Build a system supporting self-modification!
How to build a system which allows to change its
structure and behavior dynamically?!
!
Introduce two levels: base level with application logic
and meta level with data about structure and behavior!
P
S
C
47. Domain Logic Patterns!
Development of an enterprise application!
How to structure business logic of the application?!
• Transaction Script!
Simple procedural approach to data processing!
• Domain Model!
Object-oriented domain logic modeling!
• Table Module!
Data store table-oriented modeling!
P
C
S
51. Data Source Patterns!
Development of an enterprise application!
How to organize the access to the database?!
• Table/Row Data Gateway!
Provide class representing each table (table row) of database!
• Active Record!
Add data manipulation methods to domain model objects!
• Data Mapper!
Add a layer of mappers to decouple model and data scheme!
P
C
S
52. OrderGateway
+findAll(): RecordSet
+find(id): RecordSet
+update(id, date, total)
+insert(date, total)
+delete(id)
Table Data Gateway!
sql = “SELECT * FROM Orders”;
cmd = new DbCommand(sql, cn);
return cmd.GetRecordSet();
id details
1
2
Orders
- Use with Table Module
- DTO over RecordSet
- Views over Tables
53. OrderGateway
+customerId: long
+date: datetime
+findAll(): OrderGateway[]
+find(id): OrderGateway
+update()
+insert()
+delete()
Row Data Gateway!
sql = “SELECT * FROM Orders”;
cmd = new DbCommand(sql, cn);
return load(cmd.GetRecordSet());
id details
1
2
Orders
- No domain logic
- Finder class for finds
- Auto-generated code
54. Order
+customerId: long
+date: datetime
+findAll(): Order[]
+find(id): Order
+update()
+insert()
+delete()
+getTotal(): decimal
Active Record!
sql = “SELECT * FROM Orders”;
cmd = new DbCommand(sql, cn);
return load(cmd.GetRecordSet());
id details
1
2
Orders
- Has domain logic
- Couples domain to DB
- Use for simple logic
56. Unit of Work!
Organize optimal access to data source!
How to manage object changes to avoid multiple
database calls and shorten transaction span?!
!
Maintain the list of affected objects, flushing the
changes at once considering consistency issues!
P
S
C
58. Repository!
Organize access to data source!
How to simplify domain objects accessing interface to
work with them in collection-like way?!
!
Create intermediate abstraction layer between domain
and data mappers acting like in-memory collection!
P
S
C
59. IRepository<T>
Find(Criteria): IList<T>
Insert(obj: T)
Update(obj: T)
Delete(obj: T)
Repository!
EntityFrameworkReposity<T>
-context: DbContext
#Table: DbSet<T>
OrderReposity
#Table: DbSet<Order>
- Acts like in-memory collection
- Criteria allows to build queries
- Mock to in-memory in unit test
60. Web Controller Patterns!
Web application with MVC architecture!
How to handle requests in a web application?!
• Page Controller!
A controller per each web app page!
• Front Controller!
Single controller for the entire web app!
!
P
C
S
63. Web View Patterns!
Web application user interface!
How to render resulting HTML responding to request?!
• Template View!
HTML template with markers for rendering logic!
• Transform View!
Transform domain data into HTML markup!
• Tow Step View!
Turn domain data into HTML markup in two steps!
P
C
S
64. Template View!
Order
+lines: List<OrderLine>
+total(): decimal
OrderHelper
lineDetail(line): String
totalStr(): String
- Usually server page (php, aspx, jsp)
- Avoid logic in template
- Put all logic in helper
OrderDetails.tmpl
…
<ul {foreach(l in lines)}>
<li>{lineDetail(l)}</li>
</ul>
<b>{totalStr()}</b>
…
65. Transform View!
Order
+lines: List<OrderLine>
+total(): decimal
Transformer
+transformOrder(ord)
- Domain objects => xml (json) => html
- XSLT transformation is dominant
- Harder to write, easier to test
HTML
read create
66. Two Step View!
Order
+lines: List<OrderLine>
+total(): decimal
OrderStageFirst
+renderOrder(ord)
+renderOrderLine(line)
- Domain objects => logical view => html
- Gives flexibility in result html formatting
- Allows several target representations
HTML
read create
OrderView
+lines: List<Row>
+total(): Field
OrderStageSecond
+renderView(orderView)
+renderRow(orderRow)
read create
68. Creational Patterns!
• Abstract Factory!
Provides interface for creating families of related objects!
• Builder!
Separates construction of complex object from representation!
• Factory Method!
Defines method to create instance not specifying exact class!
• Singleton!
Ensures a class has only one instance with global access to it!
!
!
72. Singleton!
Environment
-instance: Environment
-variables: EnvVariable[]
+getInstance(): Environment
+getVariables(): EnvVariable[]
Environment getInstance() {
if(instance == null)
instance = new Environment();
return instance;
}
- Don’t overuse (introduces global state)
- Consider concurrency issues with static
- Hard to test and reuse
Antipattern?
73. Structural Patterns!
• Adapter!
Converts a class interface into another expected interface!
• Composite!
Composes objects into tree structure to treat them uniformly!
• Decorator!
Attaches new responsibilities to a class avoiding subclassing!
• Façade!
Provides unified interface to a subsystem!
• Proxy!
Provides a surrogate for an object to control access to it!
!
!
79. Behavioral Patterns!
• Chain of Responsibility!
Chain of objects passing the request until an object handles it!
• Command!
Encapsulate the request in the object!
• Observer!
A subject notifies observing objects about its state changes!
• Strategy!
Encapsulate algorithms to make behavior changeable!
• Template Method!
Defines the skeleton of an algorithm redefining steps in children !
• Visitor!
Represents an operation to be performed on elements!
!
87. References!
• Frank Buschmann Pattern-Oriented Software Architecture!
• Craig Larman Applying UML and Patterns!
• Martin Fowler Patterns of Enterprise Application Architecture!
• Gang of Four Design Patterns!
• Gregor Hohpe, Bobby Woolf Enterprise Integration Patterns!
• Kent Beck Implementation Patterns!