Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde V: Software Engineering II

56
Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde V: Software Engineering II Köln 27. Januar 2011

description

Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde V: Software Engineering II. Köln 27. Januar 2011. Design Patterns. Eine „Kunstlehre“, die auf der Objektorientierung aufsetzt ... - PowerPoint PPT Presentation

Transcript of Softwaretechnologie für Fortgeschrittene Teil Thaller Stunde V: Software Engineering II

  • Softwaretechnologie fr FortgeschritteneTeil Thaller

    Stunde V: Software Engineering II

    Kln 27. Januar 2011

  • Design Patterns*Eine Kunstlehre, die auf der Objektorientierung aufsetzt ...

    so verbreitet, dass ich mir erlaubt habe, zwei sehr geringfgig modifizierte Vorlesungsfolien auswrtiger Kollegen zu benutzen.

  • Design PatternsCS 406 Software Engineering IFall 2001

    Aditya P. Mathur

    Purdue UniversityOctober 30, 2001

    CCC-VR 5

  • CS 406: Design Patterns *Organization

    Patterns:

    Behavioral:Observer

    Structural:Faade

    Creational Abstract FactoryFactory MethodSingletonExcellent reference:

    Design Patterns book by Erich Gamma, et al., Addison-Wesley, 1994.

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern [2]

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern [3]

    CCC-VR 5

  • CS 406: Design Patterns *Class collaboration in Observer

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern: Observer codeclass Subject;

    class observer {

    public:

    virtual ~observer;protected:

    virtual void Update (Subject* theChangedSubject)=0;observer ();

    };

    CCC-VR 5

  • CS 406: Design Patterns *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;

    };

    CCC-VR 5

  • CS 406: Design Patterns *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);

    }

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern: A Concrete Subject [1]class ClockTimer : public Subject {

    public:virtual int GetHour();}

    virtual int GetMinutes();

    virtual int GetSecond();

    ClockTimer();void Tick ();

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern: A Concrete Subject [2]ClockTimer :: Tick {

    // Update internal time keeping state.// gets called on regular intervals by an internal timer.

    }

    Notify();

    CCC-VR 5

  • CS 406: Design Patterns *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*);

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern: A Concrete Observer [2]DigitalClock ::DigitalClock (ClockTimer* s) {

    _subject = s;

    }

    _subjectAttach(this);DigitalClock ::~DigitalClock() {

    _subject->Detach(this);}

    CCC-VR 5

  • CS 406: Design Patterns *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.// Code for drawing the digital clock.

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern: Main (skeleton)ClockTimer* timer = new ClockTimer;

    DigitalClock* digitalClock = new DigitalClock (timer);

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *Observer Pattern: ConsequencesAbstract 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 others presence. In some cases this may lead to unwanted updates.

    CCC-VR 5

  • CS 406: Design Patterns *Facade Pattern: Problem

    CCC-VR 5

  • CS 406: Design Patterns *Facade Pattern: SolutionFacade

    CCC-VR 5

  • CS 406: Design Patterns *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.Faade 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 faade can be a single entry point to each subsystem level. This allows layering.

    CCC-VR 5

  • CS 406: Design Patterns *Facade Pattern: Participants and CommunicationClients communicate with subsystem classes by sending requests to faade. Faade forwards requests to the appropriate subsystem classes.Clients do not have direct access to subsystem classes.Participants: Faade and subsystem classes

    CCC-VR 5

  • CS 406: Design Patterns *Facade Pattern: BenefitsPromotes 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.

    CCC-VR 5

  • CS 406: Design Patterns *Example: A compilerExpressionNodeStatementNode

    CCC-VR 5

  • CS 406: Design Patterns *Faade 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.

    CCC-VR 5

  • CS 406: Design Patterns *Faade Pattern: Code [2]class parser {

    public:

    Parser ();virtual ~Parser()};

    virtual void Parse (Scanner&, PNodeBuilder&);// Builds a parse tree from tokens using the PNodeBuilder.

    CCC-VR 5

  • CS 406: Design Patterns *Faade Pattern: Code [3]class Pnodebuilder {

    public:

    Pnodebuilder ();// Builds a parse tree incrementally. Parse tree // consists of Pnode objects.// Node for a variable.// Node for an assignment.// Similarly...more nodes.

    CCC-VR 5

  • CS 406: Design Patterns *Faade Pattern: Code [4]class Pnode {

    public:

    // An interface to manipulate the program node and its children.

    CCC-VR 5

  • CS 406: Design Patterns *Faade Pattern: Code [5]class CodeGenerator {

    public:

    // Generate bytecode.

    CCC-VR 5

  • CS 406: Design Patterns *Faade 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);

    CCC-VR 5

  • CS 406: Design Patterns *Faade Pattern: Code [7]class Compiler {

    public:

    // Faade. Offers a simple interface to compile and// Generate code.}

    CCC-VR 5

  • CS 406: Design Patterns *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?

    CCC-VR 5

  • CS 406: Design Patterns *Facade Pattern: Another Example [2]Calls to this faade are placed near the start of the methods that need to be validated. Example: Invoke the faade 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).

    CCC-VR 5

  • CS 406: Design Patterns *Toolkits and FrameworksToolkits: Collection of related and reusable classes e.g. C++ I/O stream libraryFramework: A set of cooperating classes that make up a reusable design for a specific class of applications e.g. drawing, compilers, CAD/CAM etc.

    CCC-VR 5

  • CS 406: Design Patterns *Toolkits and FrameworksAdvantages 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?

    CCC-VR 5

  • CS 406: Design Patterns *Abstract Factory: The Problem1.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?

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *Abstract Factory: Solution[2]

    CCC-VR 5

  • CS 406: Design Patterns *Abstract Factory: Solution[2]

    CCC-VR 5

  • CS 406: Design Patterns *Abstract Factory Pattern: Participants and CommunicationConcreteFactory: 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 objectsClient: Uses only the interface declared by the abstractFactory and AbstractProduct classes.

    CCC-VR 5

  • CS 406: Design Patterns *Abstract Factory Pattern: Code [1]class MazeFactory {

    public:

    MazeFactory();// Creates components of mazes. // Builds rooms, walls, and doors.}// more methods.// This factory is a collection of // factory methods. Also, this class// acts both as Abstract and Concrete // Factory

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *Factory Method: The Problem [1]1.Frameworks use abstract classes to define and maintain relationships between objects2.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.

    CCC-VR 5

  • CS 406: Design Patterns *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!

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • CS 406: Design Patterns *Factory Method: Solution[2]

    CCC-VR 5

  • CS 406: Design Patterns *Factory Method Pattern: Structure

    CCC-VR 5

  • CS 406: Design Patterns *Factory Method Pattern: Participants and CommunicationConcreteProduct (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.

    CCC-VR 5

  • CS 406: Design Patterns *Other Patterns: SingletonOne 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.

    CCC-VR 5

  • CS 406: Design Patterns *Singleton StructureSingleton

    CCC-VR 5

  • CS 406: Design Patterns *Singleton Code [1]class Singleton {

    }// Only one instance can ever be created.

    CCC-VR 5

  • CS 406: Design Patterns *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.

    CCC-VR 5

  • *Herzlichen Dank!

    ******************************