850 likes | 1.04k Views
INF5120 Modellbasert Systemutvikling. F09: Service Design - GRASP Patterns, Design Patterns, SOA Patterns and Refactoring Forelesning 31.03.2008 Arne-Jørgen Berre. Agenda. Lectures and reading text (pensum) Patterns – history (Alexander) GRASP patterns (Lairman)
E N D
INF5120Modellbasert Systemutvikling F09: Service Design - GRASP Patterns, Design Patterns, SOA Patterns and Refactoring Forelesning 31.03.2008 Arne-Jørgen Berre
Agenda • Lectures and reading text (pensum) • Patterns – history (Alexander) • GRASP patterns (Lairman) • Design Patterns (Gang of 4) • SOA: Concepts, Technology and Design (Erl) • SOA: Principles of Service Design (Erl) • SOA: Design Patterns (Erl) • Refactoring (Fowler)
Lectures • 1: 21/1: Introduction to MBSU, MDA, OO and Service/SOA modeling (AJB) • 2: 28/1: Business Process Modeling (CIM) - with BPMN (AJB) • 3: 4/2: Metamodeling and UML profiles, MDA technologies (EMF/GMF) – BPMN example (BRE) • 4: 11/2: Language Engineering and DSL – SOA Example (BRE) • 5: 18/2: Model transformations with ATL and QVT – and JEE (GO) • 6: 25/2: SOA Architectures and UPMS (PIM) (AJB) • 7: 3/3: Method Engineering and Service Modeling/SEMET (BRE) • 8: 10/3: Code generation with MOFScript and other technologies (GO) • EASTER • 9 :31/3:: Service Design and Patterns (AJB) • 10: 7/4: PIM and Web Services teknologi (PSM) med WSDL/XML/BPEL (PSM) (BRE, GO) • 11: 14/4: Model Driven Interoperability (BRE) • 12: 21/4: Model Driven Interoperability and agent technologies (BRE, Ismar) • 13: 28/4: Ontologies, Semantic web and Semantic Service Modeling (AJB) • 14: 5/5: Aspect-oriented Programming and Modeling (ARS) • 15: 26/5 Course summary • Exam: June 2nd, 2008… • AJB – Arne J. Berre, BRE – Brian Elvesæter, GO – Gøran Olsen, ARS – Arnor Solberg
SOA pattern literature web references www.soapatterns.com basis in: www.whatissoa.com www.SOAPrinciples.com www.SOAMethodology.com www.SOAGlossary.com www.soabooks.com www.soamag.com
Analysis Design Implementation Architecture Patterns (Macro Architecture) Analysis (Domain) Patterns Domain Framework Idioms (Language dependent patterns) Design Patterns (Micro Architecture) (OO) Reusable Components Patterns: From Analysis to Implementation
Module level patterns: Architecture Patterns Collaboration level patterns: Design Patterns Refactoring Object level patterns: GRASP Patterns on various design levels SOA Design patterns *
Patterns • Patterns - konsepter og prinsipper • Basis GRASP patterns • Analyse/Domene patterns • Design patterns • Arkitektur patterns • System integrasjons patterns • Refactoring • Antipatterns
Alexander - Patterns Christopher Alexander “A Pattern Language”, Oxford University Press, 1977 “The Timeless Way of Building”, 1979 • A way to capture the essence of good architecture • Each pattern describes a problem and its solution • A pattern language is a group of interacting patterns • Difficult in practice - The creative process is as important as the patterns
What are patterns? • "A solution to a problem in a context"? • Insufficient, says the “Gang of Four” (GOF) • What’s missing? 3 things: • Recurrence • Teaching (e.g., implementation consequences, trade-offs, and variations) • A name • GOF: • Patterns contain 4 essential elements • pattern name • problem • solution • consequences • Christopher Alexander (as quoted in the GOF book): • "Each pattern describes a problem which occurs over and over again ... and then describes the core of [a] 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."
Pattern Description Template • Name • Classification • Rationale • Applicability • Description • Diagram • Steps/Process • Implementation • Variants • Examples (incl code) • Discussion Patterns are ideally described using Ooram (UML) role models !! (See later)
Architectural patterns and style • Architect Christopher Alexander • “Quality without a name” – from The Timeless Way of Building, 1979 • A Pattern Language: Towns, Buildings, Construction (Center for Environmental Structure Series), 1977 • Ref. SW Engineering later: Design patterns, analysis patterns, architectural patterns
Trends: The Waves of Client/Server Technology – towards SOA Second Wave First Wave Third Wave Fourth Wave Fifth Wave MDA, Web Services, .Net Service-oriented Architecture SOAP, XML WSDL/WSFL Server-side componentsc Distributed Objects Database Servers File Servers Groupware J2EE/EJB COM+ Corba Comp OMG CORBA COM/OLE Web/Internett Java TP Monitors 1982 1986 1990 1994 1998 1999 2000 2001 … 2005 P2P Grid Base Source: Client/Server Survival Guide, 1994, 1996 Robert Orfali, Dan Harkey OS/2 Edition, VNR Computer library + AJB update 2005 Agents, FIPA
GRASP General Responsibility Assignment Software Patterns. Responsibility assignment. 1. knowing (answering) 2. or, doing Guidance and evaluation in mechanistic design. • 1. Expert • 2. Creator • 3. Controller • 4. Low Coupling • 5. High Cohesion • 6. Polymorphism • 7. Pure Fabrication • 8. Indirection • 9. Don’t Talk to • Strangers
Controller GRASP • What class should receive a system event message? • Assign the responsibility for handling a system event message to one of these choices: • The business or “organization” (a façade controller). • or, The overall “system” or aggregate concept (a façade controller). • or, An artificial class representing the use case (a use case controller).
Expert GRASP • Most general purpose responsibility assignment principle? • Assign a responsibility to the information expert—the class that has the information necessary to fulfill the responsibility. • “That which knows, does” • Who has the most data/information for solving the problem?
Expert • To “have the information” means, for example, the object may: • know it as an attribute or object reference • be able to derive it • What is the motivation for Expert? • Looking for task-owners that support encapsulation and low coupling. • This reduces change impacts.
High Cohesion GRASP • How to design classes to increase the likelihood of reuse and not be overwhelmingly complex? • Assign responsibilities so that cohesion remains high.
Low Coupling GRASP • How to create reusable components that are resilient to change? • Assign responsibilities so that coupling remains low.
GRASP Polymorphism • How to handle alternatives based on type? • When related alternatives or behaviors vary by type (class), • assign responsibility for the behavior—using polymorphic operations—to the types for which the behavior vary.
GRASP Other GRASP Patterns • 1. Expert • 2. Creator • 3. Controller • 4. Low Coupling • 5. High Cohesion • 6. Polymorphism • 7. Pure Fabrication • 8. Indirection • 9. Don’t Talk to • Strangers • for more information... • Creator—who creates? Usually the aggregate or containing object. • Pure Fabrication— “design” objects. Make it up when desperate. • Indirection— “most problems in computer science …” • Don’t Talk to Strangers—Law of Demeter
Quick overview of Design Principles • The Open-Closed Principle • by Bertrand Meyer • The Dependency Inversion Principle • by Robert C. Martin • The Liskov Substitution Principle • by Barbara Liskov • The Interface Segregation Principle • by Robert C. Martin
The Open-Closed Principle • Software should be “open” for extension but “closed” to modification • The goal is to design software that be easily extended without changing any of the existing code • Inheritance and the development of abstract base classes play a big role in trying to fulfill this goal
Button PushButton The 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 ButtonClient Lamp Button and ButtonClient can now vary independently!
The Liskov Substitution Principle • Functions that use base class interfaces must not depend on or be confused by any derivatives of those interfaces • A logical extension of the Open-Closed Principle • All subclasses should implement the interface of the base class in a manner consistent with the intent of the base class
The Interface Segregation Principle • Clients should not be forced to depend on interfaces that they do not use • The principle here is to avoid cluttering up an interface with things (functions, inheritance relationships) that the clients don’t need to use • Take a clients’ perspective!!
Design patterns BookGamma/Helm/Johnson/Vlissides (GoF): Design Patterns, 1995 R. Ryan:, D. Rosenstrauch:Design Patterns in Java, 1997
What are patterns? • "A solution to a problem in a context"? • Insufficient, says the “Gang of Four” (GOF) • What’s missing? 3 things: • Recurrence • Teaching (e.g., implementation consequences, trade-offs, and variations) • A name • GOF: • Patterns contain 4 essential elements • pattern name • problem • solution • consequences • Christopher Alexander (as quoted in the GOF book): • "Each pattern describes a problem which occurs over and over again ... and then describes the core of [a] 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."
Design Pattern A design pattern describes a basic scheme for structuring subsystems and components of a software architecture as well as their relationships. It identifies, names, and abstracts a common structural or functional principle by describing its different parts, their collaboration and responsibilities.
GOF (Gang of Four) 23 Patterns • Creational Patterns (5) • Abstract Factory, Builder, Factory Method, Prototype, Singleton • Structural Patterns (7) • Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy • Behavioural Patterns (11) • Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor
Skylight Spelunker • “Skylight Spelunker” is a Java framework for a file browser similar in appearance to the “Windows Explorer” included with Windows 98. • Spelunker has two views: • Disks and folders in tree structure (FolderView - Left pane) • All contents of selected folder (ContentsView - Right pane) • Spelunker provides support for : • Multiple ways of arranging ContentsView icons • Accessing network drives as well as local • Deleting, renaming and viewing disk contents
ContentsView FolderView Windows Explorer Screen Shot
Patterns in Spelunker example • Composite • used to model the file tree data structure • Strategy • used to layout the file and folder icons in ContentsView • Observer • used to re-display FolderViews and ContentsViews after user requests • Proxy and State • used to model password-protected network disk drives • Command • used to carry out user requests
The “Composite” pattern • Problem • What is the best way to model the Spelunker file tree? • The Spelunker file tree is a classic tree structure. Thus we need a leaf class (File) and a tree class (Folder) which contains pointers to the Files and Folders in it. • However, there are many operations that are relevant to both a File and a Folder (e.g., getSize()). • The user doesn’t treat Files and Folders differently, so why should calling modules have to? • The design would be less complex and more flexible if the calling module could initiate operations on a target object, without knowing whether the target was a File or a Folder. • File and Folder should share a common interface.
The “Composite” pattern • How the pattern solves the problem • Intent • “Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” [GHJV94] • Explanation • The Composite pattern works by having leaf and tree objects share a common interface. • Create an abstract base class (or interface) that represents both File and Folder. • Files and Folders need to provide implementations for the same operations, but they can implement them differently. • E.g., leaves usually handle an operation directly, while trees usually forward the operation to its children (and/or perform additional work before or after forwarding)
Component Client Operation( ) children Add(Component) Remove(Component) GetChild(int) Leaf Composite Operation( ) for all g in children g.Operation(); Operation( ) Add(Component) Remove(Component) GetChild(int) The “Composite” pattern • How the pattern solves the problem, cont. • Gang of Four UML [GHJV94]
Node Resource Tree children getSize( ) File Folder getSize( ) size = total of size of each child getSize() getContents() The “Composite” pattern • Use of the pattern in Spelunker • Both File and Folder share a common interface: Node. • Spelunker UML
The “Composite” pattern • Use of the pattern in Spelunker, cont. • Code examples public class File extends Node { private long size = 0; public long getSize() { return size; } } public class Folder extends Node { private Vector contents; public long getSize() { long size = 0; if (contents != null) { Enumeration e = contents.elements(); while (e.hasMoreElements()) { size += ((Node)e.nextElement()).getSize(); } } return size; } }
The “Strategy” pattern • Problem • The way in which the icons are arranged varies according to user preference - the user may choose an iconic view only, or a short/long detail view. • Including the algorithms to arrange the icons as methods in ContentsView would make it cumbersome to add new icon arrangement algorithms to ContentsView; ContentsView would have to be subclassed and some implementation details might have to be unnecessarily exposed. • A switch statement would most likely be used to choose the correct arrangement algorithm.
The “Strategy” pattern • How the pattern solves the problem • Intent • “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” [GHJV94] • Explanation • The algorithms for arranging the icons are encapsulated into a separate interface. • The correct arrangement algorithm is chosen polymorphically. • ContentsView neither knows nor cares which arrangement is presently in use.
strategy Context Strategy ContextInterface() AlgorithmInterface() ConcreteStrategyA ConcreteStrategyB ConcreteStrategyC AlgorithmInterface() AlgorithmInterface() AlgorithmInterface() The “Strategy” pattern • How the pattern solves the problem, cont. • Gang of Four UML [GHJV94]
strategy ContentsView ViewManager updateVisibleNodes() updateVisibleNodes() IconViewManager ListViewManager updateVisibleNodes() updateVisibleNodes() The “Strategy” pattern • Use of the pattern in Spelunker • ContentsView delegates the task of arranging the icons to ViewManager. • Spelunker UML
The “Strategy” pattern • Use of the pattern in Spelunker, cont. • Code examples public interface ViewManager { public void updateVisibleNodes(Folder activeFolder); } public class ContentsView extends ResourceTreeView { private ViewManager viewManager; public void showIconView() { viewManager = new IconViewManager(this); } public void showListView(boolean showDetail) { viewManager = new ListViewManager(this, showDetail); } public void updateVisibleNodes(Folder activeFolder) { viewManager.updateVisibleNodes(activeFolder); } }
The “Observer” pattern • Problem • What is the best way to keep all views of the file tree in sync? • We need to be able to re-draw the display window after the user modifies a file/folder (e.g., when user clicks on a folder to select it) • However, there may be several windows and panes that display the same file/folder. We need to re-draw all of them. • To do this, the tree needs to keep a list of all of its views, and notify each one after a modification is done. • However, the tree and view objects might: • have little other relationship besides this notification • need to have their code modified independently • need to be reused separately • So it would be preferable not to make them too tightly coupled to each other.
The “Observer” pattern • How the pattern solves the problem • Intent • “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.” [GHJV94] • Explanation • The Observer pattern works by defining an abstract class (or interface) with a single method signature. The method will be used as a mechanism for “observer” objects to be notified of changes in their “subject”. • Concrete observer sub-classes will each provide their own implementation of what to do when the notification occurs. • The subject can notify each observer the same way, without caring which specific sub-class of observer the object actually is.
Observer Subject Update( ) Attach(Observer) observers Detach(Observer) Notify( ) ConcreteSubject ConcreteObserver SubjectState ObserverState subject Update( ) GetState( ) ObserverState = subject.GetState() return SubjectState for all o in observers o.update(); The “Observer” pattern • How the pattern solves the problem, cont. • Gang of Four UML [GHJV94]
resourceTreeChanged(Folder) observers ResourceTree ResourceTreeView activeFolder AttachObserver(ResourceTreeObserver) resourceTreeChanged( Folder activeFolder) DetachObserver(ResourceTreeObserver) subject NotifyObservers( ) updateVisibleNodes(activeFolder); repaint(); Enumeration e = observers.elements(); while (e.hasMoreElements()) { ResourceTreeObserver o = (ResourceTreeObserver)e.nextElement(); o.resourceTreeChanged(activeFolder); } The “Observer” pattern • Use of the pattern in Spelunker • ResourceTree notifies all ResourceTreeViews whenever its state is modified. • Spelunker UML ResourceTreeObserver
The “Observer” pattern • Use of the pattern in Spelunker, cont. • Code examples public class ResourceTree { private Vector observers; public void setActiveFolder(Folder folder) { if (activeFolder != folder) { activeFolder = folder; notifyObservers(); } } public void notifyObservers() { Enumeration e = observers.elements(); while (e.hasMoreElements()) { ((ResourceTreeObserver)e.nextElement()).resourceTreeChanged(activeFolder); } } } public abstract class ResourceTreeView extends Panel implements ResourceTreeObserver { public void resourceTreeChanged(Folder activeFolder) { updateVisibleNodes(activeFolder); repaint(); } }