Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde VI: Software Engineering II Köln 22. Januar 2015.

Slides:



Advertisements
Similar presentations
Creational Design Patterns. Creational DP: Abstracts the instantiation process Helps make a system independent of how objects are created, composed, represented.
Advertisements

Creational Patterns (2) CS350/SE310 Fall, Lower the Cost of Maintenance Economic Goal Coupling-Cohesion, Open-Close, Information-Hiding, Dependency.
Creational Patterns, Abstract Factory, Builder Billy Bennett June 11, 2009.
Copyright © Active Frameworks Inc. - All Rights Reserved - V2.0Creational Patterns - Page L4-1 PS95&96-MEF-L11-1 Dr. M.E. Fayad Creationa l Paradigm.
Design Patterns CS 406 Software Engineering I Fall 2001 Aditya P. Mathur Purdue University October 30, 2001.
 Recent researches show that predicative programming can be used to specify OO concepts including classes, objects, interfaces, methods, single and multiple.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Overview of Design Patterns
CSE3308/CSC Software Engineering: Analysis and DesignLecture 5B.1 Software Engineering: Analysis and Design - CSE3308 Patterns CSE3308/CSC3080/DMS/2000/12.
Plab – Tirgul 12 Design Patterns
CSE Software Engineering: Analysis and Design, 2005Lecture 8A.1 Software Engineering: Analysis and Design - CSE3308 Design and Analysis Patterns.
Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
CSE Software Engineering: Analysis and Design, 2002Lecture 7B.1 Software Engineering: Analysis and Design - CSE3308 Patterns CSE3308/DMS/2002/15.
Design Patterns Based on Design Patterns. Elements of Reusable Object-Oriented Software. by E.Gamma, R. Helm, R. Johnson,J. Vlissides.
Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde V: Software Engineering II Köln 28. Januar 2010.
Design Patterns Examples in C++ Moshe Fresko Bar-Ilan University Object Oriented Programming
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
© SERG Software Design (OOD Patterns) Object-Oriented Design Patterns Topics in Object-Oriented Design Patterns Compliments of Spiros Mancoridis Material.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Abstract Factory Pattern.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Design Patterns.
SENG 422 Lab 2 Design Patterns Time: ELW B220 from (4:00 - 6:50) every Tuesday TA: Philip Baback Alipour Ph.D. Candidate in Electrical, Computer Engineering.
Creational Patterns (1) CS350, SE310, Fall, 2010.
02 - Creational Design Patterns Moshe Fresko Bar-Ilan University תשס"ח 2008.
Software Components Creational Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
Facade Introduction. Intent Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the.
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.
The Factory Method Design Pattern Motivation: Class / Type separation – Abstract class serves as type definition and concrete class provides implementation.
Abstract Factory and Factory Method CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
Proxy, Observer, Symbolic Links Rebecca Chernoff.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Structural Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
OO Methodology Elaboration Iteration 2 - Design Patterns -
Design Patterns Solving problems with already known solutions Unit - 13.
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Design Pattern. Definition: A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
Manali Joshi1 The Observer Design Pattern Presented By: Manali Joshi.
Model View Controller Architectural Pattern and Observer Pattern
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
The Facade Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
CS 5150 Software Engineering Lecture 16 Program Design 3.
 Creational design patterns abstract the instantiation process.  make a system independent of how its objects are created, composed, and represented.
The Abstract Factory Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Abstract Factory pattern Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Software Architecture and Design BITS C461/IS C341 Software Engineering First Semester Aditya P. Mathur Department of Computer Science Purdue.
Overview of Design Patterns
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
Software Design & Documentation
Factory Patterns 1.
Observer Design Pattern
Design Patterns with C# (and Food!)
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
Presented by Igor Ivković
Design Patterns - A few examples
Software Engineering Lecture 7 - Design Patterns
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
Lesson 5: More on Creational Patterns
Creational Patterns.
Presented by Igor Ivković
Presentation transcript:

Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde VI: Software Engineering II Köln 22. Januar 2015

Design Patterns 2 (1)Eine „Kunstlehre“, die auf der Objektorientierung aufsetzt... (2)… so verbreitet, dass ich mir erlaubt habe, eine weitere, noch weniger modifizierte Vorlesungsfolienserie eines auswärtigen Kollegen zu benutzen: FjAD&url=https%3A%2F%2Fwww.cs.purdue.edu%2Fhomes%2Fapm%2Fcourses%2 FBITSC461-fall03%2Fuml-slides%2Fdesign- patterns.ppt&ei=TarAVI38OMvYPZ_BgLAM&usg=AFQjCNH40- I5Tg2vClieMxp2AopiwFMOCQ&sig2=tk2-1WCelWo8D5AxOE68Yw

Design Patterns CS 406 Software Engineering I Fall 2001 Aditya P. Mathur Purdue University October 30, 2001

CS 406: Design Patterns4 Organization Patterns: Behavioral: Observer Structural: Façade Creational Abstract Factory Factory Method Singleton Excellent reference: Design Patterns book by Erich Gamma, et al., Addison-Wesley, 1994.

CS 406: Design Patterns5 Design Patterns [1] A solution to a problem that occurs repeatedly in a variety of contexts. Each pattern has a name. Use of each pattern has consequences.

CS 406: Design Patterns6 Design Patterns [2] Generally at a “higher level” of abstraction. Not about designs such as linked lists or hash tables. Generally descriptions of communicating objects and classes.

Sequenz geändert CS 406: Design Patterns7

8 Other Patterns: Singleton One may use a global variable to access an object but it does not prevent one from creating more than one instance. Instead the class itself is made responsible for keeping track of its instance. It can thus ensure that no more than one instance is created. This is the singleton pattern. Used to ensure that a class has only one instance. For example, one printer spooler object, one file system, one window manager, etc.

CS 406: Design Patterns9 Singleton Structure Singleton static Instance() SingletonOp() GetSingletonData() static uniqueInstance singletonData return uniqueinstance

CS 406: Design Patterns10 Singleton Code [1] class Singleton { public: static Singleton* Instance(); } protected: Singleton(); private: Static Singleton* _instance // Only one instance can ever be created. // Creation hidden inside Instance().// Cannot access directly.

CS 406: Design Patterns11 Singleton Code [2] Singleton* Singleton::_instance=0; Singleton* Singleton:: Instance(){ if (_instance ==0) { _instance=new Singleton; } Return _instance; } // Clients access the singleton // exclusively via the Instance member // function.

Sequenz wieder hergestellt CS 406: Design Patterns12

CS 406: Design Patterns13 Observer Pattern [1] Need to separate presentational aspects with the data, i.e. separate views and data. Classes defining application data and presentation can be reused. Change in one view automatically reflected in other views. Also, change in the application data is reflected in all views. Defines one-to-many dependency amongst objects so that when one object changes its state, all its dependents are notified.

CS 406: Design Patterns14 Observer Pattern [2] A=10% B=40% C=30% D=20% Application data A B C D ADCB Relative Percentages Y X Z A B C D Change notification Requests, modifications

CS 406: Design Patterns15 Observer Pattern [3] Subject attach (Observer) detach (Observer) Notify () Observer Update() Concrete Observer Update() observerState Concrete Subject GetState() SetState() subjectState observers subject For all x in observers{ x  Update(); } observerState= subject  getState();

CS 406: Design Patterns16 Class collaboration in Observer : ConcreteSubject :ConcreteObserver-1:ConcreteObserver-2 GetState() Notify() Update() SetState() GetState() Update()

CS 406: Design Patterns17 Observer Pattern: Observer code class Subject; class observer { public: virtual ~observer; protected: virtual void Update (Subject* theChangedSubject)=0; observer (); Note the support for multiple subjects. }; Abstract class defining the Observer interface.

CS 406: Design Patterns18 Observer Pattern: Subject Code [1] class Subject { public: virtual ~Subject; protected: Subject (); virtual void Attach (observer*); virtual void Detach (observer*) ; virtual void Notify(); private: List *_observers; }; Abstract class defining the Subject interface.

CS 406: Design Patterns19 Observer Pattern: Subject Code [2] void Subject :: Attach (Observer* o){ _observers -> Append(o); } void Subject :: Detach (Observer* o){ _observers -> Remove(o); } void Subject :: Notify (){ ListIterator iter(_observers); } for ( iter.First(); !iter.IsDone(); iter.Next()) { iter.CurrentItem() -> Update(this); }

CS 406: Design Patterns20 Observer Pattern: A Concrete Subject [1] class ClockTimer : public Subject { public: virtual int GetHour(); } virtual int GetMinutes(); virtual int GetSecond(); ClockTimer(); void Tick ();

CS 406: Design Patterns21 Observer Pattern: A Concrete Subject [2] ClockTimer :: Tick { // Update internal time keeping state. // gets called on regular intervals by an internal timer. } Notify();

CS 406: Design Patterns22 Observer Pattern: A Concrete Observer [1] class DigitalClock: public Widget, public Observer { public: DigitalClock(ClockTimer*); virtual ~DigitalClock(); virtual void Draw(); private: } ClockTimer* _subject; virtual void Update(Subject*); Override Observer operation.Override Widget operation.

CS 406: Design Patterns23 Observer Pattern: A Concrete Observer [2] DigitalClock ::DigitalClock (ClockTimer* s) { _subject = s; } _subject  Attach(this); DigitalClock ::~DigitalClock() { _subject->Detach(this); }

CS 406: Design Patterns24 Observer Pattern: A Concrete Observer [3] void DigitalClock ::Update (subject* theChangedSubject ) { If (theChangedSubject == _subject) { } Draw(); } void DigitalClock ::Draw () { int hour = _subject->GetHour(); } int minute = _subject->GeMinute(); // etc. Check if this is the clock’s subject. // Code for drawing the digital clock.

CS 406: Design Patterns25 Observer Pattern: Main (skeleton) ClockTimer* timer = new ClockTimer; DigitalClock* digitalClock = new DigitalClock (timer);

CS 406: Design Patterns26 When to use the Observer Pattern? When an abstraction has two aspects: one dependent on the other. Encapsulating these aspects in separate objects allows one to vary and reuse them independently. When a change to one object requires changing others and the number of objects to be changed is not known. When an object should be able to notify others without knowing who they are. Avoid tight coupling between objects.

CS 406: Design Patterns27 Observer Pattern: Consequences Abstract coupling between subject and observer. Subject has no knowledge of concrete observer classes. (What design principle is used?) Support for broadcast communication. A subject need not specify the receivers; all interested objects receive the notification. Unexpected updates: Observers need not be concerned about when then updates are to occur. They are not concerned about each other’s presence. In some cases this may lead to unwanted updates.

CS 406: Design Patterns28 Facade Pattern: Problem Client Classes Subsystem classes Need to communicate with

CS 406: Design Patterns29 Facade Pattern: Solution Client Classes Subsystem classes Facade

CS 406: Design Patterns30 Facade Pattern: Why and What? Need to provide a simple interface to many, often small, classes. But not necessarily to ALL classes of the subsystem. Façade provides a simple default view good enough for most clients. Facade decouples a subsystem from its clients. Subsystems often get complex as they evolve. A façade can be a single entry point to each subsystem level. This allows layering.

CS 406: Design Patterns31 Facade Pattern: Participants and Communication Clients communicate with subsystem classes by sending requests to façade. Façade forwards requests to the appropriate subsystem classes. Clients do not have direct access to subsystem classes. Participants: Façade and subsystem classes

CS 406: Design Patterns32 Facade Pattern: Benefits Promotes weak coupling between subsystem and its clients. Helps in layering the system. Helps eliminate circular dependencies. Shields clients from subsystem classes; reduces the number of objects that clients deal with.

CS 406: Design Patterns33 Example: A compiler StackMachineCodegeneratorRISCCodegeneratorStream BytecodeStream CodeGenerator ScannerTokenParserSymbolPnodeBuilderPnode ExpressionNode StatementNode Compiler Compile() Invocations

CS 406: Design Patterns34 Façade Pattern: Code [1] class Scanner { public: Scanner (istream&); Private: virtual Scanner(); istream& _inputStream; }; virtual Token& Scan(); // Takes a stream of characters and produces a stream of tokens.

CS 406: Design Patterns35 Façade Pattern: Code [2] class parser { public: Parser (); virtual ~Parser() }; virtual void Parse (Scanner&, PNodeBuilder&); // Builds a parse tree from tokens using the PNodeBuilder.

CS 406: Design Patterns36 Façade Pattern: Code [3] class Pnodebuilder { public: Pnodebuilder (); virtual Pnode* NewVariable ( ) const; Char* variableName // Builds a parse tree incrementally. Parse tree // consists of Pnode objects. virtual Pnode* NewAssignment ( ) const; Pnode* variable, Pnode* expression // Node for a variable. // Node for an assignment. // Similarly...more nodes. Private: Pnode* _node; };

CS 406: Design Patterns37 Façade Pattern: Code [4] class Pnode { public: // An interface to manipulate the program node and its children. PNode(); protected: }; virtual void GetSourcePosition (int& line, int& index); // Manipulate program node. virtual void Add (Pnode*); // Manipulate child node. virtual void Remove (Pnode*); // …. virtual void traverse (Codegenerator&); // Traverse tree to generate code.

CS 406: Design Patterns38 Façade Pattern: Code [5] class CodeGenerator { public: // Generate bytecode. virtual void Visit (StatementNode*); // Manipulate program node. // …. virtual void Visit (ExpressionNode*); Protected: CodeGenerator (BytecodeStream&); }; BytecodeStream& _output;

CS 406: Design Patterns39 Façade Pattern: Code [6] void ExpressionNode::Traverse (CodeGenerator& cg) { cg.Visit (this); ListIterator i(_children); For (i.First(); !i.IsDone(); i.Next();{ i.CurrentItem()  Traverse(cg); };

CS 406: Design Patterns40 Façade Pattern: Code [7] class Compiler { public: // Façade. Offers a simple interface to compile and // Generate code. Compiler (); } virtual void Compile (istream&, BytecodeStream&); void Compiler:: Compile (istream& input, BytecodeStream& output) { Scanner scanner (input); PnodeBuilder builder; Parser parser; parser.Parse (scanner, builder); RISCCodeGenerator generator (output); Pnode* parseTree = builder.GetRootNode(); parseTree  Traverse (generator); } Could also take a CodeGenerator Parameter for increased generality.

CS 406: Design Patterns41 Facade Pattern: Another Example from POS [1] –Only one item can be purchased using a gift certificate. –Hence, subsequent enterItem operations must be invalidated in some cases. (Which ones?) –Suppose that when a new Sale is created, it will be paid by a gift certificate Assume that rules are desired to invalidate an action: How does a designer factor out the handling of such rules?

CS 406: Design Patterns42 Facade Pattern: Another Example [2] Calls to this façade are placed near the start of the methods that need to be validated. –Example: Invoke the façade to check if a new salesLineItem created by makeLineItem is valid or not. (See page 370 of Larman.) It evaluates a set of rules against an operation and indicates if the rule has invalidated an operation. Define a “rule engine” subsystem (e.g. POSRuleEngineFacade).

CS 406: Design Patterns43 Toolkits and Frameworks Toolkit Main body of an Application Calls a procedure or A method Framework Reuse the main body of an Application and write the code it calls Defines the architecture Of the application Toolkits: Collection of related and reusable classes e.g. C++ I/O stream library Framework: A set of cooperating classes that make up a reusable design for a specific class of applications e.g. drawing, compilers, CAD/CAM etc.

CS 406: Design Patterns44 Toolkits and Frameworks Advantages and disadvantages of using frameworks. 2.What is more difficult to design: Application, toolkit, or frameworks? 3.How do changes in framework effect an application? 1.When using frameworks, what defines the architecture of the application? 4.How do design patterns differ from frameworks?

CS 406: Design Patterns45 Abstract Factory: The Problem 1.Consider a user interface toolkit to support multiple look- and-feel standards. 2.For portability an application must not hard code its widgets for one look and feel. How to design the application so that incorporating new look and feel requirements will be easy?

CS 406: Design Patterns46 Abstract Factory Pattern: Solution[1] 2.This class declares an interface to create different kinds of widgets. 1.Define an abstract WidgetFactory class. 3.There is one abstract class for each kind of widget and concrete subclasses implement widgets for different standards. 4.WidgetFactory offers an operation to return a new widget object for each abstract widget class. Clients call these operations to obtain instances of widgets without being aware of the concrete classes they use.

CS 406: Design Patterns47 Abstract Factory: Solution[2] WidgetFactory CreateScrollbar() CreateWindow() WindowScrollBar WWidgetFactory MacWidgetFactory Client WWindowMacWindow MacScrollBarWScrollBar One for each standard.

CS 406: Design Patterns48 Abstract Factory: Solution[2] AbstractFactory CreateScrollbar() CreateWindow() ConcreteFactory1 Client ProductA1ProductA2 AbstractProductA ProductB2ProductB1 AbstractProductB ConcreteFactory2 CreateProductA() CreateProductB()

CS 406: Design Patterns49 Abstract Factory Pattern: Participants and Communication ConcreteFactory: Implements the operations to create concrete product objects. AbstractProduct: Declares an interface for a type of product object. ConcreteProduct: Defines a product object to be created by the corresponding factory. AbstractFactory: Declares the interface for operations to create abstract product objects Client: Uses only the interface declared by the abstractFactory and AbstractProduct classes.

CS 406: Design Patterns50 Abstract Factory Pattern: Code [1] class MazeFactory { public: MazeFactory(); virtual Maze* MakeMaze() const { return new Maze;} // Creates components of mazes. // Builds rooms, walls, and doors. virtual Wall* MakeWall() const { return new Wall;} virtual Wall* MakeRoom(int n) const { return new Room;} } // more methods. // This factory is a collection of // factory methods. Also, this class // acts both as Abstract and Concrete // Factory

CS 406: Design Patterns51 Abstract Factory Pattern: Code [1] Maze* MazeGame:: CreateMaze (MazeFactory& factory) Maze* aMaze = factory.MakeMaze(); // Builds a maze. } Room* myroom = factory.MakeRoom(1); Door* aDoor = factory.MakeDoor(myRoom,herRoom) Room* herroom = factory.MakeRoom(2); aMaze  AddRoom(myRoom) aMaze  AddRoom(herRoom) // More code to add walls. // One can also create a // BombedMazeFactory with // different types of Rooms // and Walls.

CS 406: Design Patterns52 Factory Method: The Problem [1] 1.Frameworks use abstract classes to define and maintain relationships between objects 2.Consider a framework for applications that present multiple documents to the user. A drawing application is an example. 3.This framework defines two abstract classes: application and document. These ought to be sub classed by clients for application specific implementation. 4.The application class will create and manage documents when required, e.g. when a New command is selected from the menu.

CS 406: Design Patterns53 Factory Method Pattern: The Problem [2] 5.Document sub class is application specific. Hence the Application class does not know what kind of document to create! 6.Problem: The framework must instantiate classes but it only knows about the abstract classes, which it cannot initiate!

CS 406: Design Patterns54 Factory Method Pattern: Solution[1] 2.Application subclasses redefine an abstract CreateDoc() method to return the appropriate Document subclass. 1.The Factory Method pattern encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework. 3.When an Application is instantiated, it can instantiate application specific Documents without knowing their class.

CS 406: Design Patterns55 Factory Method: Solution[2] Document Open() Close() Save() Application CreateDoc() NewDoc() OpenDoc() MyApplication CreateDoc() MyDocument Document* doc=CreateDoc(); docs.Add(doc); doc  Open(); docs 1 * Factory method

CS 406: Design Patterns56 Factory Method Pattern: Structure Product Creator FactoryMethod() SomeOperation() ConcreteCreator FactoryMethod() ConcreteProduct product=Factory method Return new ConcreteProduct

CS 406: Design Patterns57 Factory Method Pattern: Participants and Communication ConcreteProduct (MyDocument): Implements the Product interface. Creator (Application): Declares factory method which returns an object of type Product. Also, may define the factory method to create a Product object. ConcreteCreator (MyApplication): Overrides the factory method to return an instance of a ConcreteProduct. Product (Document): Defines the interface of objects the factory method creates.

58 Herzlichen Dank!