Design Patterns Elements of Reusable Object-Oriented Software

Slides:



Advertisements
Similar presentations
Design Patterns.
Advertisements

Design Patterns based on book of Gang of Four (GoF) Erich Gamma, Richard Helm, Ralph Johnson, and John VlissidesGang of Four (GoF) Elements of Reusable.
©Ian Sommerville 2000 Software Engineering, 6th edition. Chapter 12Slide 1 Software Design l Objectives To explain how a software design may be represented.
Design Patterns based on book of Gang of Four (GoF) Erich Gamma, Richard Helm, Ralph Johnson, and John VlissidesGang of Four (GoF) Elements of Reusable.
Plab – Tirgul 12 Design Patterns
Dept. of Computer Engineering, Amirkabir University of Tech. 1 Design Patterns Dr. Noorhosseini Introduction.
Design Patterns CS is not simply about programming
James Tam Introduction To Design Patterns You will learn about design techniques that have been successfully applied to different scenarios.
Satzinger, Jackson, and Burd Object-Orieneted Analysis & Design
Spring 2010CS 2251 Design Patterns. Spring 2010CS 2252 What is a Design Pattern? "a general reusable solution to a commonly occurring problem in software.
Application Architectures Vijayan Sugumaran Department of DIS Oakland University.
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Design Patterns Discussion of pages: xi-11 Sections: Preface, Forward, Chapter
Design Patterns Alan Shalloway, James Trott, Design Patterns Explained, Addison-Wesley, Gamma, Helm, Johnson, Vlissides, Design Patterns, Elements.
Design Patterns.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
Case Studies on Design Patterns Design Refinements Examples.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
January 12, Introduction to Design Patterns Tim Burke References: –Gamma, Erich, et. al. (AKA, The Gang of Four). Design Patterns: Elements of Reusable.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Y2 eProjects Session 4 – Advanced Topics. Objectives  Dynamic Models  Design Patterns (Optional)  Software testing (for S4) ACCP i7.1\Sem3_4\eProject\T4.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
ECE450S – Software Engineering II
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
FacadeDesign Pattern Provide a unified interface to a set of interfaces in a subsystem. Defines a high level interface that makes the subsystem easier.
CS616: Software Engineering Spring 2009 Design Patterns Sami Taha.
Design Pattern. Definition: A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
Design Patterns Introduction
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
The Facade Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Patterns in programming
Design Patterns: MORE Examples
The Object-Oriented Thought Process Chapter 15
Chapter 10 Design Patterns.
Software Design Patterns
MPCS – Advanced java Programming
Introduction to Design Patterns
Design Patterns Lecture part 2.
Introduction to Design Patterns
Software Design and Architecture
object oriented Principles of software design
Presented by Igor Ivković
Software Engineering Lecture 7 - Design Patterns
Object Oriented Design Patterns - Creational Patterns
Object Oriented Design Patterns - Structural Patterns
DESIGN PATTERNS : Introduction
Introduction to Design Patterns
Informatics 122 Software Design II
Presented by Igor Ivković
Presentation transcript:

Design Patterns Elements of Reusable Object-Oriented Software based on book of Gang of Four (GoF) Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides Elements of Reusable Object-Oriented Software Dragos Comaneci(dragos@comaneci.ro) 1

INTRODUCTION 2 2

UML class diagram recall Interface Abstract Concrete # private * protected + public static Package Class1 Class2 ClassN # private() * protected() + public() abstract() static() name(Type1, Type2) : RetType code derived base aggregator aggregatee creator product caller/user callee/used 3 3

What is a Design Pattern? A design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object- oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. 4 4

OK, but what is it? Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern. Intent: A description of the goal behind the pattern and the reason for using it. Also Known As: Other names for the pattern. Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used. Applicability: Situations in which this pattern is usable; the context for the pattern. Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose. Participants: A listing of the classes and objects used in the pattern and their roles in the design. Collaboration: A description of how classes and objects used in the pattern interact with each other. Consequences: A description of the results, side effects, and trade offs caused by using the pattern. Implementation: A description of an implementation of the pattern; the solution part of the pattern. Sample Code: An illustration of how the pattern can be used in a programming language. Known Uses: Examples of real usages of the pattern. Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns. 5 5

Classification Creational Structural Behavioral Abstract Factory Adapter Null Object Factory method Bridge Command Builder Composite Interpreter Lazy instantiation Decorator Iterator Object pool Façade Mediator Prototype Flyweight Memento Singleton Proxy Observer Multiton State Resource acquisition is initialization Chain of responsibility Strategy Specification Template method Visitor 6 6

Model-View-Controller Classification / 2 Concurrency J2EE Architectural Active Object Business Delegate Layers Balking Composite Entity Presentation-abstraction-control Double checked locking Composite View Three-tier Guarded suspension Data Access Object Pipeline Monitor object Fast Lane Reader Implicit invocation Reactor Front Controller Blackboard system Read/write lock Intercepting Filter Peer-to-peer Scheduler Model-View-Controller Event-Based Asynchronous Service Locator Service-oriented architecture Thread pool Session Facade Naked objects Thread-specific storage Transfer Object Value List Handler View Helper 7 7

Contents Simple patterns Complex patterns J2EE patterns Singleton Template Method Factory Method Adapter Proxy Iterator Complex patterns Abstract Factory Strategy Mediator Façade J2EE patterns Data Access Objects Model-View-Controller Session Façade Front Controller 8 8

SIMPLE PATTERNS 9 9

Singleton Ensure a class has only one instance, and provide a global point of access to it. public class Singleton { private Singleton() {} private static Singleton _instance = null; public static Singleton getInstance () { if (_instance == null) _instance = new Singleton(); return _instance; } ... multiton named instances double-checked locking: Singleton getInstance() { if(_instance == null) { lock(Singleton.class) { } return _instance; Lazy instantiation Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. return _instance; 10 10

Template Method Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. ... operation1(); operation2(); operationN(); void Application::OpenDocument (const char* name) { if (!CanOpenDocument(name)) { // cannot handle this document return; } Document* doc = DoCreateDocument(); if (doc) { _docs->AddDocument(doc); AboutToOpenDocument(doc); doc->Open(); doc->DoRead(); 11 11

Factory Method Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. ... Product product = CreateProduct(); AKA: Virtual constructor Factory methods are usually called within Template Methods. In the document example above, NewDocument is a template method. a class can't anticipate the class of objects it must create. a class wants its subclasses to specify the objects it creates. classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. class MazeGame { public: Maze* CreateMaze(); virtual Maze* MakeMaze() const { return new Maze; } virtual Room* MakeRoom(int n) const { return new Room(n); } virtual Wall* MakeWall() const { return new Wall; } virtual Door* MakeDoor(Room* r1, Room* r2) const { return new Door(r1, r2); } }; return new ConcreteProduct(); 12 12

_adaptee.SpecificRequest(); Adapter Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. AKA: Wrapper -> Java primitive wrappers: Boolean, Double, Integer, … you want to use an existing class, and its interface does not match the one you need. you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces. (object adapter only) you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class. _adaptee.SpecificRequest(); 13 13

_realService.someOperation(); Proxy Provide a surrogate or placeholder for another object to control access to it. An adapter provides a different interface to the object it adapts. In contrast, a proxy provides the same interface as its subject. A remote proxy provides a local representative for an object in a different address space. A virtual proxy creates expensive objects on demand. The ImageProxy described in the Motivation is an example of such a proxy. A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights. A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed. _realService.someOperation(); 14 14

return ConcreteIterator(this); Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. AKA: Cursor to access an aggregate object's contents without exposing its internal representation. to support multiple traversals of aggregate objects. to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration). Who controls the iteration? When the client controls the iteration, the iterator is called an external (active) iterator, and when the iterator controls it, the iterator is an internal (passive) iterator. external: foreach(…) internal: obj.iterate(Action<T> body); A robust iterator ensures that insertions and removals won't interfere with traversal, and it does it without copying the aggregate. Additionally SkipTo(); Who defines the traversal algorithm? The iterator is not the only place where the traversal algorithm can be defined. The aggregate might define the traversal algorithm and use the iterator to store just the state of the iteration. We call this kind of iterator a cursor. Null iterators. A NullIterator is a degenerate iterator that's helpful for handling boundary conditions. By definition, a NullIterator is always done with traversal; that is, its IsDone operation always evaluates to true. return ConcreteIterator(this); 15 15

COMPLEX EXAMPLES 16 16

Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes. AKA: Kit a system should be independent of how its products are created, composed, and represented. a system should be configured with one of multiple families of products. a family of related product objects is designed to be used together, and you need to enforce this constraint. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations. return new ProductA1(); return new ProductA2(); return new ProductB1(); return new ProductB2(); 17 17

_strategy.Algorithm(); Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. _strategy.Algorithm(); AKA: Policy many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors. you need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms. an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures. a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class. Motivation: Clients that need linebreaking get more complex if they include the linebreaking code. That makes clients bigger and harder to maintain, especially if they support multiple linebreaking algorithms. Different algorithms will be appropriate at different times. We don't want to support multiple linebreaking algorithms if we don't use them all. It's difficult to add new algorithms and vary existing ones when linebreaking is an integral part of a client. 18 18

Mediator Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand. reusing an object is difficult because it refers to and communicates with many other objects. a behavior that's distributed between several classes should be customizable without a lot of subclassing. 19 19

Façade Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. Package1 Class1 Package2 Class3 Motivation: Compiler you want to provide a simple interface to a complex subsystem. there are many dependencies between clients and the implementation classes of an abstraction. you want to layer your subsystems. Class c1 = new Class1(); Class c2 = new Class2(); Class c3 = new Class3(); c1.doStuff(c2); c3.setProp(c1.getProp2()); return c3.doStuff2(); Package3 Class2 20 20

http://java.sun.com/blueprints/patterns/catalog.html J2EE PATTERN EXAMPLES 21 21

Data Access Objects (DAO) Code that depends on specific features of data resources ties together business logic with data access logic. This makes it difficult to replace or modify an application's data resources. This pattern separates a data resource's client interface from its data access mechanisms; adapts a specific data resource's access API to a generic client interface; allows data access mechanisms to change independently of the code that uses the data. 22 22

Data Access Objects (DAO) / 2 BusinessObject: represents the data client. DataAccessObject: abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. DataSource: represents a data source implementation. TransferObject: the data carrier, DAO may use it to return data to the client. Enables Transparency Enables Easier Migration Reduces Code Complexity in Business Objects Centralizes All Data Access into a Separate Layer Not Useful for Container-Managed Persistence Adds Extra Layer Needs Class Hierarchy Design 23 23

Model-View-Controller (MVC) Application presents content to users in numerous ways containing various data. The engineering team responsible for designing, implementing, and maintaining the application is composed of individuals with different skill sets. 24 24

Model-View-Controller / 2 State query State change Change notification Re-use of Model components Easier support for new types of clients Increased design complexity View selection User gestures 25 25

Front Controller The presentation-tier request handling mechanism must control and coordinate processing of each user across multiple requests. Such control mechanisms may be managed in either a centralized or decentralized manner. Problems: Each view is required to provide its own system services, often resulting in duplicate code. View navigation is left to the views. This may result in commingled view content and view navigation. Distributed control is more difficult to maintain: changes will need to be made in numerous places. 26 26

Front Controller / 2 Web container incoming request handle request return response create model render response return control delegate rendering of response handle request Centralizes Control Improves Manageability of Security Improves Reusability 27 27

Session Façade Enterprise beans encapsulate business logic and business data and expose their interfaces, and thus the complexity of the distributed services, to the client tier. Tight coupling, which leads to direct dependence between clients and business objects; Too many method invocations between client and server, leading to network performance problems; Lack of a uniform client access strategy, exposing business objects to misuse. 28 28

Session Façade / 2 Client: the object which needs access to the business service. This client can be another session bean (Session Facade) in the same business tier or a business delegate in another tier. SessionFacade: a session bean which manages the relationships between numerous BusinessObjects and provides a higher level abstraction to the client. BusinessObject: a role object that facilitates applying different strategies, such as session beans, entity beans and a DAO. A BusinessObject provides data and/or some services. Introduces Business-Tier Controller Layer Exposes Uniform Interface Reduces Coupling, Increases Manageability Improves Performance, Reduces Fine-Grained Methods Provides Coarse-Grained Access Centralizes Security Management Centralizes Transaction Control Exposes Fewer Remote Interfaces to Clients 29 29

OUTRODUCTION 30 30

Revision Simple patterns Complex patterns J2EE patterns Singleton Template Method Factory Method Adapter Proxy Iterator Complex patterns Abstract Factory Strategy Mediator Façade J2EE patterns Data Access Objects Model-View-Controller Session Façade Front Controller 31 31

Questions? 32 32

Sources http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley- Professional/dp/0201633612 http://en.wikipedia.org/wiki/Design_pattern_(computer_science) http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science) http://java.sun.com/blueprints/patterns/catalog.html http://java.sun.com/blueprints/patterns/DAO.html http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html http://java.sun.com/blueprints/patterns/MVC.html http://java.sun.com/blueprints/patterns/SessionFacade.html http://java.sun.com/blueprints/corej2eepatterns/Patterns/SessionFacade.html http://java.sun.com/blueprints/patterns/FrontController.html http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html 33 33