+ All Categories
Home > Documents > Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im...

Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im...

Date post: 16-Oct-2020
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
174
Softwaretechnik Entwurfsmuster (Patterns) Prof. Dr. Matthias H¨ olzl Joschka Rinke 9. Dezember 2015
Transcript
Page 1: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Softwaretechnik

Entwurfsmuster (Patterns)

Prof. Dr. Matthias Holzl

Joschka Rinke

9. Dezember 2015

Page 2: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Entwurfsmuster

Page 3: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Grundlagen

Dasselbe (bewahrte) Losungsmuster kann fur Probleme, dieeinander ahnlich sind, wiederverwendet werden.

Muster

Problemlösung 1 Problemlösung 2 Problemlösung 3

Abstraktion Anwendung

Page 4: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Vorteile

I Wiederverwendung von erprobten Losungsprinzipien(Qualitat, Kostenersparnis)

I abstrakte Dokumentation von Entwurfen

I gemeinsames Vokabular zur (schnellen) Verstandigung unterEntwicklern

Page 5: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Nachteile

I Oftmals erhohte Komplexitat

I Oftmals weniger statische Information

I Oftmals geringere Performance

Page 6: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Architekturpattern (C. Alexander)

Window Place

Everybody loves window seats, bay windows, and big windows withlow sills and comfortable chairs drawn up to them. . .

A room which does not have a place like this seldom allows you tofeel comfortable or perfectly at ease. . .

If the room contains no window which is a “place,” a person in theroom will be torn between two forces: 1. He wants to sit down andbe comfortable. 2. He is drawn toward the light. Obviously, if thecomfortable places—those places in the room where you mostwant to sit—are away from the windows, there is no way ofovercoming this conflict. . .

Therefore: In every room where you spend any length of timeduring the day, make at least one window into a “window place.”

Page 7: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

What is a pattern? (C. Alexander)

Each pattern is a three-part rule, which expresses a relationbetween a certain context, a problem, and a solution.

As an element in the world, each pattern is a relationship betweena certain context, a certain system of forces which occursrepeatedly in that context, and a certain spatial configurationwhich allows these forces to resolve themselves.

As an element of language, a pattern is an instruction, whichshows how this spatial configuration can be used, over and overagain, to resolve the given system of forces, wherever the contextmakes it relevant.

The pattern is, in short, at the same time a thing, which happensin the world, and the rule which tells us how to create that thing,and when we must create it. It is both a process and a thing;both a description of a thing which is alive, and a description ofthe process which will generate that thing.

Page 8: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Komponenten eines Patterns

Context

ProblemForces

Solution

Page 9: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Geschichte

I 1977 Alexander: Architekturmuster fur Gebaude undStadtebau

I 1980 Smalltalks MVC-Prinzip (Model View Controller)

I Seit 1990 Objektorientierte Muster im Software-Engineering

I 1995 Design Pattern Katalog von Gamma, Helm, Johnson,Vlissides (

”Gang of Four“, GoF)

I Martin Fowler (1996). Analysis Patterns

I Frank Buschmann et al. (1996-2007(?)). Pattern-OrientedSoftware Architecture, Volumes 1–5

I Martin Fowler (2002). Patterns of Enterprise ApplicationArchitecture

I Gregor Hohpe, Bobby Woolf (2003). Enterprise IntegrationPatterns: Designing, Building, and Deploying MessagingSolutions

Page 10: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Arten von Pattern

Pattern konnen in verschiedenen Abstraktionsgraden definiertwerden:

I Architektur-Pattern: Beschreiben die komplette Architektureines Systems

Beispiele: Geschichtete Architektur,”Pipes und Filter“

Architektur

I Design-Pattern: Beschreiben Losungen fur Design-Problemeauf einer niedrigeren Abstraktionsebene alsArchitektur-Pattern

Beispiele: Singleton, Abstract Factory, Composite

I Idiome: Beschreiben Sprachspezifisch Losungen.

Beispiele: Smart Pointers (C/C++), Resource Allocation isInitialization (RAII, C++)

Page 11: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Beispiel: GUI in Smalltalk 80

Page 12: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

MVC Architektur

Smalltalk 80 war eine der ersten graphischenProgrammierumgebungen. Um die Entwicklung graphischerOberflachen zu vereinfachen wurde in den 1980er Jahren inSmalltalk 80 die Model-View-Controller (MVC)-Architektureingefuhrt.

Es wurden viele Varianten des ursprunglichen MVC Patternsvorgeschlagen (e.g., Model-View-Presenter,Model-Document-Abstraction, Model-View-Viewmodel). Leiderwerden viele dieser Varianten oft ebenfalls als MVC-Patternbezeichnet.

Page 13: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

MVC Architektur

Name: Model-View-Controller

Kontext:

Sie entwickeln eine Applikation mit graphischer Benutzeroberflacheund wollen Benutzeroberflache und Geschaftslogik unabhangigvoneinander halten.

Problem:

Wenn man den Code, der die Benutzeroberflache verwaltet direktin die Geschaftslogik einer Anwendung einbettet erhalt manAnwendungen, deren eigentliche Funktionalitat eng mit derPrasentation der Daten verwoben ist. Das Erschwert dieUnterstutzung verschiedener Plattformen und verkompliziert dieGeschaftslogik.

Page 14: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

MVC Architektur

Losung:

Spalte die Anwendung in drei Arten von Objekten/Komponentenauf:

I Das Modell ist verantwortlich dafur, die Geschaftsprozesse undDomanenobjekte abzubilden, und es verarbeitet die Datenentsprechend den geschaftsspezifischen Anforderungen. DasModell hangt nicht von spezifischen Ein-Ausgabeverhaltenoder Benutzeroberflachen ab.

I View-Komponenten sind fur die graphische Darstellung derDaten verantwortlich. Sie erhalten die anzuzeigenden Datenvom Modell. Mehrere Views konnen die gleichen Daten desModells darstellen.

I Jede View hat einen oder mehrere Controller, die Eingabenvom Benutzer bekommen. Diese Eingaben werden in Eventsfur die View oder das Modell umgewandelt. JeglicheBenutzerinteraktion wird durch Controller geregelt.

Page 15: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

MVC Architektur

Struktur: (Kein UML Diagramm!)

Page 16: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

MVC Architektur

Interaktion (Kommunikationsdiagramm):

5: update()1: attach()

6: getData()4: service()

3: manipulate()

2: handleEvent() 7: showData()

:Controller

:Model

:View

Page 17: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

MVC Architektur

Konsequenzen:

I Modell und Benutzeroberflache sind vollstandig entkoppelt

I Es konnen leicht verschiedene Benutzeroberflachen fur diegleiche Geschaftslogik erstellt werden

I Das Modell muss einen generischen Notifikationsmechanismusbereitstellen um Views und Controller uber Anderungeninformieren zu konnen

Page 18: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Web-MVC Architektur

InputController View

ApplicationController

userinput

displayoutput

viewmessages

modelaccess and

editingchange

notificationchange

notification

BusinessObjects

changenotification

modelaccess and

editing

Page 19: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Web-MVC Architektur

Viele andere Architekturen wurden in der Literatur ebenfalls alsMVC-Architektur bezeichnet. Z.B. wird in Web-Applikationen oftder

”Application Controller“ im Diagramm auf der vorhergehenden

Folie als”Controller“ bezeichnet. In einer traditionellen

MVC-Architektur ist der”Application Controller“ Teil des Modells

und kein Controller.

Page 20: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Alternative zu Web-MVC: Flux

Views

Dispatcher Store(s)

ControllerViews

changenotification

changenotification

userinput

changeevents

actiondispatch

displayoutput

displayoutput

Page 21: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Alternative zu Web-MVC: Flux

Page 22: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Andere Anwendung eines MVC-Artigen Patterns

Page 23: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Pattern-Sprachen und -Kataloge

I Pattern werden zu verschiedenen Zwecken und aufverschiedenen Abstraktionsebenen verwendet

I Daher gibt es verschiedene”Pattern-Sprachen,“ die sich in

den Elementen unterscheiden, die fur jedes Patternaufgeschrieben werden

I Typischerweise werden nicht einzelne Pattern aufgeschriebensondern Sammlungen miteinander verwandter Patterns, diealle in der gleichen Pattern-Sprache notiert sind

I Eine solche Sammlung von Patterns nennt sichPattern-Katalog

I Pattern-Kataloge existieren fur verschiedenartigeThemengebiete

I Analyse, Software-Design, . . .I Enterprise-Architektur, verteilte Systeme, . . .I Programmiersprachen (JavaScript, Smalltalk. . . )

Page 24: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Wesentliche Elemente eines Entwurfmusters

I Name des Musters

I Beschreibung der Problemklasse, bei der das Musteranwendbar ist

I Beschreibung eines Anwendungsbeispiels

I Beschreibung der Losung (Struktur, Verantwortlichkeiten, ...)

I Beschreibung der Konsequenzen (Nutzen/Kosten-Analyse)

Page 25: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Beispiel: Design-Pattern im GoF-Katalog

Beschreibungsform fur Design Pattern

I Pattern Name and ClassificationThe pattern’s name conveys the essence of the patternsuccinctly. A good name is vital, because it will become partof your design vocabulary.

I IntentA short statement that answers the following question: Whatdoes the design pattern do? What is its rational and intent?What particular design issue or problem does it address?

I Also Known AsOther well-known names for the pattern, if any.

Page 26: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Beispiel: Design-Pattern im GoF-Katalog

I MotivationA scenario that illustrates a design problem and how the classand oject structures in the pattern solve the problem. Thescenario will help you understand the more abstractdescriptions of the pattern that follows.

I ApplicabilityWhat are the situations in which the design pattern can beapplied? What are examples of poor designs that the patterncan address? How can you recognize these situations?

I StructureA graphical representation of the classes in the pattern using anotation based on the Object Modelling Technique (OMT).We also use interaction diagrams to illustrate sequences ofrequests and collaborations between objects.

Page 27: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Beispiel: Design-Pattern im GoF-Katalog

I ParticipantsThe classes and/or objects participating in the design patternand their responsibilities.

I CollaborationsHow the participants collaborate to carry out theirresponsibilities.

I ConsequencesHow does the pattern support its objectives? What are thetrade-offs and results of using the pattern? What aspects ofsystem structure does it let you vary independently?

I ImplementationWhat pitfalls, hints, or techniques should you be aware ofwhen implementing the pattern? Are there language-specificissues?

Page 28: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Beispiel: Design-Pattern im GoF-Katalog

I Sample CodeCode fragments that illustrate how you might implement thepattern in C++ or Smalltalk.

I Known UsesExamples of the pattern found in real systems. We include atleast two examples from different domains.

I Related PatternsWhat design patterns are closely related to this one? Whatare the important differences? With which other patternsshould this one be used?

Page 29: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Klassifikation der GoF Design Pattern

I Creational Patterns (befassen sich mit der Erzeugung vonObjekten)

I Structural Patterns (befassen sich mit der strukturellenKomposition von Klassen oder Objekten)

I Behavorial Patterns (befassen sich mit der Interaktion vonObjekten und der Verteilung von Verantwortlichkeiten)

Page 30: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Creational Patterns

I Abstract Factory Provide an interface for creating families ofrelated or dependent objects without specifying their concreteclasses.

I Builder Separate the construction of a complex object fromits representation so that the same construction process cancreate different representations.

I Factory Method Define an interface for creating an object,but let subclasses decide which class to instantiate. FactoryMethod lets a class defer instantiation to subclasses.

I Prototype Specify the kinds of objects to create using aprototypical instance, and create new objects by copying thisprototype.

I Singleton Ensure a class only has one instance, and provide aglobal point of access to it.

Page 31: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Structural Patterns

I Adapter Convert the interface of a class into anotherinterface clients expect. Adapter lets classes work togetherthat couldn‘t otherwise because of incompatible interfaces.

I Bridge Decouple an abstraction from its implementation sothat the two can vary independently.

I Composite Compose objects into tree structures to representpart-whole hierarchies. Composite lets clients treat individualobjects and compositions of objects uniformly.

Page 32: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Structural Patterns

I Decorator Attach additional responsibilities to an objectdynamically. Decorators provide a flexible alternative tosubclassing for extending functionality.

I Facade Provide a unified interface to a set of interfaces in asubsystem. Facade defines a higher-level interface that makesthe subsystem easier to use.

I Flyweight Use sharing to support large numbers offine-grained objects efficiently.

I Proxy Provide a surrogate or placeholder for another objectto control access to it.

Page 33: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Behavioral Patterns

I Chain of Responsibility Avoid coupling the sender of arequest to its receiver by giving more than one object achance to handle the request. Chain the receiving objects andpass the request along the chain until an object handles it.

I Command Encapsulate a request as an object, thereby lettingyou parameterize clients with different requests, queue or logrequests, and support undoable operations.

I Interpreter Given a language, define a representation for itsgrammar along with an interpreter that uses therepresentation to interpret sentences in the language.

I Iterator Provide a way to access the elements of an aggregateobject sequentially without exposing its underlyingrepresentation.

Page 34: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Behavioral Patterns

I Mediator Define an object that encapsulates how a set ofobjects interact. Mediator promotes loose coupling by keepingobjects from referring to each other explicitly, and it lets youvary their interaction independently.

I Memento Without violating encapsulation, capture andexternalize an object’s internal state so that the object can berestored to this state later.

I Observer Define a one-to-many dependency between objectsso that when one object changes state, all its dependents arenotified and updated automatically.

I State Allow an object to alter its behaviour when its internalstate changes. The object will appear to change its class.

Page 35: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Behavioral Patterns

I Strategy Define a family of algorithms, encapsulate each one,and make them interchangeable. Strategy lets the algorithmvary independently from clients that use it.

I Template Method Define the skeleton of an algorithm in anoperation, deferring some steps to subclasses. TemplateMethod lets subclasses redefine certain steps of an algorithmwithout changing the algorithm’s structure.

I Visitor Represent an operation to be performed on theelements of an object structure. Visitor lets you define a newoperation without changing the classes of the element onwhich it operates.

Page 36: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Anwendungsbeispiel: Computerspiel

Page 37: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Anwendungsbeispiel: Computerspiel

I Spieler kann verschiedenartigeBonus-Gegenstande aufsammeln

I Die Gegenstande haben unterschiedliche EffekteI Die Interaktion der Gegenstande mit dem Spieler folgt immer

dem gleichen Muster

I Die Energie des Spielers nimmt mit der Zeit ab

I Durch Aufsammeln geeigneter Gegenstande kann der Spielerseine Energie auffullen

I Es werden laufend neue Bonus-Gegenstande erzeugt und inder Welt plaziert

Page 38: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Eine Instanz des Spiels

I Das Spiel benotigt mehrere Resourcen die von verschiedenenSubsystemen aus ansprechbar sein sollen

I System-Resourcen (Bildschirm/Renderer)I Spielelemente (Figuren, Level)

I Es soll sichergestellt werden, dass jede Resource nur einmalerzeugt wird und alle Subsysteme auf die gleiche Resourcezugreifen

I Globale Variablen?

I Statische Attribute?

I Flexibler: Eine Klasse, die ihre einzige Instanz selber verwaltet.

Page 39: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Singleton (Creational Pattern)

Intent

Ensure a class has only one instance; provide a global point ofaccess to it.

Motivation

Some classes should have exactly one instance, e.g., classes thatcorrespond to unique physical resources. This instance should beeasily accessible. Singleton makes the class itself responsible forkeeping track of its single instance.

Applicability

Use the Singleton pattern when

I there must be exactly one instance of a class, and it must beaccessible to clients from a well-known access point

I the sole instance should be extensible by subclassing, andclients should be able to use an extended instance withoutmodifying their code.

Page 40: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Singleton (Creational Pattern)

Structure

Page 41: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Singleton (Creational Pattern)

Consequences

The Singleton has several benefits:

I Controlled access to sole instance.

I Reduced name space.

I Permits refinement of operations and representation.

I Permits a variable number of instances.

I More flexible than class operations.

Known uses java.lang.Runtime;org.eclipse.core.runtime.Plugin.

Example . . .

Page 42: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Singleton (Creational Pattern)

Consequences

The Singleton has several benefits:

I Controlled access to sole instance.

I Reduced name space.

I Permits refinement of operations and representation.

I Permits a variable number of instances.

I More flexible than class operations.

Known uses java.lang.Runtime;org.eclipse.core.runtime.Plugin.

Page 43: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Singleton (Creational Pattern)

Example

(Note: This is not how the Unreal Engine works.)

Page 44: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Kurze Einfuhrung in die Unreal Engine

Page 45: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

Page 46: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

I UObject erweitert C++ um Funktionalitat wie GarbageCollection und Reflection

I AActor ist die Oberklasse aller Objekte, die innerhalb einesLevels existieren konnen (Aktoren). Aktoren konnen furNetzwerkspiele zwischen Clients und Server repliziert werden.

I APawn ist die Oberklasse aller Aktoren, die durch einenSpieler oder den Computer kontrolliert werden konnen(Pawns)

I ACharacter sind Pawns, die herumlaufen konnen

Page 47: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

I AController ist die Klasse aller Controller,d.h. aller Aktoren, die die Aktion eines Pawnskontrollieren konnen. Derartige Aktionensind z.B.

I Bewegung (z.B. Gehen/Laufen/Springen)I Interaktion mit der Umgebung (z.B.

Aufheben von Gegenstanden)I Abfeuern einer WaffeI . . .

I APlayerController ubersetzt dieEingaben des Benutzers in Aktionen fur den kontrolliertenPawn

I AAIController kontrolliert den Pawn mit Hilfe einesProgramms (der sog. kunstlichen Intelligenz (KI))

Page 48: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

Page 49: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

Fur ein Spiel konnen benutzerdefinierte Unterklassen erzeugtwerden fur

I AGameMode

I AGameState

I APlayerState

I UGameInstance

I APawn (fur Spieler-Figuren)

I APlayerController (fur Spieler-Figuren)

Die Klasse der UWorld-Instanz kann nicht verandert werden.

Page 50: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

I UGameInstance reprasentiert die aktuelle Spielinstanz. Eine(indirekte) Instanz von UGameInstance wird automatischerzeugt sobald das Spiel gestartet wird und existiert bis dasSpiel beendet wird.

I UWorld reprasentiert die Umgebung, in der alle Aktoren undKomponenten existieren und erlaubt den Zugriff auf dieaktuelle Game Instance, den aktuellen Game Mode, den GameState, etc.

Page 51: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

UE4 Klassenhierarchie

I AInfo ist eine Oberklasse fur Aktoren, die keine physikalischeReprasentation im Level haben aber Informationen uber dieWelt enthalten

I AGameMode definiert die Regeln des aktuellen Spiels, dieAktoren, die im Spiel existieren, etc. (Existiert nur auf demServer.)

I AGameState stellt den relevanten Zustand des Spiels dar,z.B. wo sich die Figuren auf einem Schachbrett befinden, wieviele Punkte die einzelnen Spieler im Moment haben, usw.(Wird zwischen Server und Clients repliziert.)

I APlayerState Instanzen existieren fur alle Spieler, die aneinem Spiel beteiligt sind und werden zwischen Clients undServer repliziert

Page 52: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Wieder zuruck zu Patterns

Page 53: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Bonusitems

I Wir wollen mehrere Arten von Bonusitems (Pickups) haben,die unterschiedliche Effekte auf den Spieler haben

I Teile des Verhaltens sollen aber immer gleich bleiben

I Wir habe die Losung dieses Problems bereits bei den UMLKlassendiagrammen besprochen

Page 54: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Bonusitems

I Wir wollen mehrere Arten von Bonusitems (Pickups) haben,die unterschiedliche Effekte auf den Spieler haben

I Teile des Verhaltens sollen aber immer gleich bleiben

I Wir habe die Losung dieses Problems bereits bei den UMLKlassendiagrammen besprochen

Page 55: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Intent

Define the skeleton of an algorithm in an operation, deferring somesteps to subclasses. Template Method lets subclasses redefinecertain steps of an algorithm without changing the algorithm’sstructure.

Motivation

I An application framework that has to deal with severaldocument classes. There are some similarities, but alsodifferences between the handling of various types ofdocuments

I The framework defines concrete operations that call abstractoperations as part of their execution

I Instances of the framework implement the virtual methods

Page 56: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Applicability

I to implement the invariant parts of an algorithm once andleave it up to subclasses to implement the behavior that canvary

I when common behavior among subclasses should be factoredand localized in a common class to avoid code duplication

I to control subclasses extensions

Page 57: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Structure

Page 58: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Participants

I AbstractClass:I defines abstract primitive operations that concrete subclasses

define (hooks)I implements a template method defining the skeleton of an

algorithm

I ConcreteClass: implements the primitive operations

Page 59: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Collaborations

ConcreteClass relies on AbstractClass to implement the invariantsteps of the algorithm

Consequences

Template Methods are a fundamental technique of code reuse.They lead to an inverted control structure sometimes called the“Hollywood Principle.” It is important for template methods tospecify which operations may and which ones must be overridden.

Page 60: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Page 61: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Template Method (Behavioral Pattern)

Page 62: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Erzeugen von Bonusitems

Wahrend des Spiels werden Bonusitems erzeugt, die der Spieleraufsammeln kann.

I Verschiedenartige Bonusitems sollen verschiedenenAuswirkungen auf den Spieler haben

I An verschiedenen Orten sollen unterschiedliche Bonusitemserzeugt werden

Die Orte, an denen Bonusitems erzeugt (”gespawned“) werden

sollen vom Level-Designer durch sognannte Spawn-Volumesfestgelegt werden.

Page 63: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Erster Entwurf: Verschiedene Spawn-Volumes

Page 64: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Factory Method (Creational Pattern)

Intent

Define an interface for creating a certain type of object; letsubclasses decide which concrete class should be instantiated.

Motivation

Consider an office suite like Microsoft Office or Libre Office. If theprograms in the suite use a common framework to manage theirdocuments, this framework has to provide functionalities formanaging documents, e.g., opening, closing, or saving them. Eachapplication has a particular type of document on which it operates,but many of the features provided by the framework areindependent of the specific document type.

Page 65: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Factory Method (Creational Pattern)

Applicability

Use the Factory Method pattern when

I A class may have to create an open-ended number ofdocument types.

I Subclasses should be responsible for creating the concretetypes.

Page 66: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Factory Method (Creational Pattern)

Structure

Page 67: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Factory Method (Creational Pattern)

Participants

I Product: The type of object that should be created (often apure interface)

I Concrete Product: Implements the Product interface

I Creator: Declares the Factory Method that returns an instanceof Product. May define a default implementation.

I Concrete Creator: Overrides the Factory Method.

Page 68: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Factory Method (Creational Pattern)

Collaborations

Creator relies on its subclasses to implement the requiredcreational method.

Consequences

I No need for application-specific classes in the framework code.

I Framework code can work with any user-defined concreteclass.

I Clients need to subclass the Creator class, thereby couplingparts of the client tightly to the framework.

I Factory Method provides hooks for subclasses.

Example . . .

Page 69: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Erzeugen von Bonusitems

Zur Erinnerung: Die Orte, an denen Bonusitems erzeugt werdensollen vom Level-Designer durch sognannte Spawn-Volumesfestgelegt werden.

Problem mit dem angegebenen DesignEs ist fur den Designer nicht moglich, den von einemSpawn-Volume erzeugten Objekttyp zu verandern.

Page 70: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Zweiter Entwurf: Konfigurierbares Spawn-Volume

Page 71: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Zweiter Entwurf: Konfigurierbares Spawn-Volume

Dieser Entwurf erlaubt die Konfiguration des erzeugten Objekts,hat aber einige Nachteile:

I Die Verwendung von Strings zur Angabe des Typs istfehleranfalligBesser: Verwendung einer Enumeration, aber dann muss furjeden neuen Pickup-Typ die Enumeration angepasst werden

I Die SpawnPickup()-Methode muss alle Pickup-Typen kennenund per Fallunterscheidung den richtigen Typ auswahlen

Page 72: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Dritter Entwurf: Spawn-Volume mit Reflection

Page 73: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Dritter Entwurf: Spawn-Volume mit Reflection

Page 74: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

From: Buschmann, Frank; Meunier, Regine; Rohnert, Hans;Sommerlad, Peter; Stal, Michael. Pattern-Oriented SoftwareArchitecture, A System of Patterns: Volume 1, p. 193. Wiley.(See also PLoPD2, p. 271)

Abstract

The Reflection architectural pattern provides a mechanism forchanging structure and behavior of software systems dynamically.It supports the modification of fundamental aspects, such as typestructures and function call mechanisms. In this pattern, anapplication is split into two parts. A meta level providesinformation about selected system properties and makes thesoftware self-aware. A base level includes the application logic. Itsimplementation builds on the meta level. Changes to informationkept in the meta level affect subsequent base-level behavior.

Page 75: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

Also Known As

Open Implementation, Meta-Level Architecture

Example

[Persistence layer for C++ that is independent of the specific typestructures used in the program.]

Context

Building systems that support their own modification a priori.

Page 76: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

Problem

Software systems evolve over time. They must be open tomodifications in response to changing technology andrequirements. Designing a system that meets a wide range ofdifferent requirements a priori can be an overwhelming task. Abetter solution is to specify an architecture that is open tomodification and extension. The resulting system can then beadapted to changing requirements on demand. In other words, wewant to design for change and evolution. Several forces areassociated with this problem:

Page 77: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

I Changing software is tedious, error prone, and often expensive.[. . . ] Software which actively supports and controls its ownmodification can be changed more effectively and more safely.

I Adaptable software systems usually have a complex innerstructure. [. . . ]. To keep such systems maintainable, we preferto hide this complexity from maintainers of the system.

I The more techniques that are necessary for keeping a systemchangeable, [. . . ], the more awkward and complex itsmodification becomes. A uniform mechanism that applies toall kinds of changes is easier to use and understand.

I Changes can be of any scale, from providing shortcuts forcommonly-used commands to adapting an applicationframework for a specific customer.

I Even fundamental aspects of software systems can change, forexample the communication mechanisms betweencomponents.

Page 78: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

Solution

Make the software self-aware, and make selected aspects of itsstructure and behavior accessible for adaptation and change. Thisleads to an architecture that is split into two major parts: a metalevel and a base level.

The meta level provides a self-representation of the software togive it knowledge of its own structure and behavior, and consists ofso-called metaobjects. Metaobjects encapsulate and representinformation about the software. Examples include type structures,algorithms, or even function call mechanisms.

The base level defines the application logic. Its implementationuses the metaobjects to remain independent of those aspects thatare likely to change. [. . . ]

Page 79: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

An interface is specified for manipulating the metaobjects. It iscalled the metaobject protocol (MOP), and allows clients tospecify particular changes[. . . ] Every manipulation of metaobjectsthrough the metaobject protocol affects subsequent base-levelbehavior, as in the function call mechanism example.

[Persistence component: metaobjects that provide run-time typeinformation, such as internal structure of objects and the layout oftheir data members.]

Page 80: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

Structure

The meta level consists of a set of metaobjects. Each metaobjectencapsulates selected information about a single aspect of thestructure, behavior, or state of the base level. [Sources formeta-level information:

I Provided by run-time of the system (Java, CLOS)

I User defined

I Retrieved from base-level at runtime]

All metaobjects together provide a self-representation of anapplication. Metaobjects make information, which is otherwise onlyimplicitly available, explicitly accessible and modifiable. [. . . ]

Page 81: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

The base level models and implements the application logic of thesoftware. Its components represent the various services the systemoffers as well as their underlying data model. [. . . ]

The base level uses the information and services provided by themetaobjects [. . . ]

The metaobject protocol (MOP) serves as an external interface tothe meta level, and makes the implementation of a reflectivesystem accessible in a defined way. [. . . ]

Page 82: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

Dynamics

It is almost impossible to describe the dynamic behavior ofreflective systems in general. We therefore present two scenariosbased on the persistence component example. [. . . ]

Implementation

[. . . ]

Variants

Reflection with several meta levels

Page 83: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

Known Uses

[CLOS, MIP, PGen, NEDIS, OLE 2.0]

Consequences

A Reflection architecture provides the following benefits:

No explicit modification of source code. [. . . ]Changing a software system is easy. [. . . ]Support for many kinds of change. [. . . ]

However, a Reflection architecture has some significant liabilities:

Modifications at the meta level may cause damage. [. . . ]Increased number of components. [. . . ]Lower efficiency. [. . . ]Not all potential changes to the software are supported [. . . ]Not all languages support reflection. [. . . ]

Page 84: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection (Architectural Pattern)

See Also

The Microkernel architectural pattern (171) supports adaptationand change by providing a mechanism for extending the softwarewith additional or customer-specific functionality.

Credits

One of the first works on reflection is the Ph.D. thesis by BrianCantwell Smith [Smi82]. This describes reflection in the context ofprocedural languages. An overview of reflective concepts can befound in [Mae87]. [. . . ]

Page 85: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Mehrere Bonusitems pro Region

Unser jetziges Design hat einige positive Eigenschaften:

I Der von einem Spawn-Volume erzeugte Pickup-Typ kannleicht geandert werden

I Das Hinzufugen von neuen Pickup-Typen geht ohne jedeAnderung an der Spawn-Volume Implementierung

Aber: Es ist nicht leicht moglich in einem Spawn-Volume mehrereBonusitem-Typen zu erzeugen.

Page 86: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Vierter Entwurf: Spawn-Volume mit Abstract Factory

Page 87: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Abstract Factory (Creational Pattern)

Intent

Provides an interface for creating families of related or dependentobjects without specifying their concrete classes.

Motivation

UI toolkit that supports multiple looks and feels. Widget look andfeel should not be hard-coded. Define an abstract WidgetFactoryclass that provides a uniform interface for creating widgets fordifferent looks and feels, instantiate a concrete subclass for eachlook and feel.

Page 88: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Abstract Factory (Creational Pattern)

Applicability

Use the Abstract Factory pattern when

I a system should be independent of how its products arecreated, composed, and represented

I a system should be configured with one of multiple families ofproducts

I a family of related product objects is designed to be usedtogether, and you need to enforce this constraint

I you want to provide a class library of products, and you wantto reveal just their interfaces, not their implementations

Page 89: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Abstract Factory (Creational Pattern)

Structure

Page 90: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Abstract Factory (Creational Pattern)

Consequences

The Abstract Factory pattern

I isolates concrete classes

I makes exchanging product families easy

I promotes consistency among products

I makes it difficult to support new kinds of products

I (significantly) increases code complexity

Known uses Toolkit in AWT.

Related Patterns

I Factory Method

I Prototype

I Singleton (the factory is often a Singleton)

Page 91: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Konfigurierbare Bonusitems

Unser jetziges Design hat einige positive Eigenschaften:

I Der von einem Spawn-Volume erzeugte Pickup-Typ kannleicht geandert werden

I Das Hinzufugen von neuen Pickup-Typen geht ohne jedeAnderung an der Spawn-Volume Implementierung

I Es konnen verschiedene Bonusitem-Typen pro Spawn-Volumeerzeugt werden

Aber: Es ist nicht leicht moglich die in einem Spawn-Volumeerzeugten Objekte zu konfigurieren.

Page 92: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Funfter Entwurf: Prototyp-Basiertes Spawn-Volume

Page 93: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Prototype (Creational Pattern)

Intent

Specify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.

Motivation

[Editor for music scores based on a general framework for graphicaleditors]

Page 94: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Prototype (Creational Pattern)

Applicability

Use the Prototype pattern when a system should be independentof how its products are created, composed, and represented; and

I when the classes to instantiate are specified at run-time, forexample, by dynamic loading; or

I to avoid building a class hierarchy of factories that parallelsthe class hierarchy of products; or

I when instances of a class can have one of only a few differentcombinations of state.

It may be more convenient to install a corresponding number ofprototypes and clone them rather than instantiating the classmanually, each time with the appropriate state.

Page 95: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Prototype (Creational Pattern)

Structure

Page 96: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Prototype (Creational Pattern)

Participants

I Prototypedeclares an interface for cloning itself

I ConcretePrototypeimplements an operation for cloning itself

I Clientcreates a new object by asking a prototype to clone itself

Collaborations

A client asks a prototype to clone itself.

Page 97: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Prototype (Creational Pattern)

Consequences

Prototype has many of the same consequences that AbstractFactory (87) and Builder (97) have: It hides the concrete productclasses from the client, thereby reducing the number of namesclients know about. Moreover, these patterns let a client work withapplication-specific classes without modification.

I Adding and removing products at run-time

I Specifying new objects by varying values

I Specifying new objects by varying structure

I Reduced subclassing

I Configuring an application with classes dynamically

The main liability of the Prototype pattern is that each subclass ofPrototype must implement the Clone operation, which may bedifficult.

Page 98: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Prototype (Creational Pattern)

Implementation and Sample Code . . .

Related Patterns

Prototype and Abstract Factory (87) are competing patterns insome ways, as we discuss at the end of this chapter. They can alsobe used together, however. An Abstract Factory might store a setof prototypes from which to clone and return product objects.

Designs that make heavy use of the Composite (163) andDecorator (175) patterns often can benefit from Prototype as well.

Page 99: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Modi

Der Designer hat sich entschieden, dass der Spieler eine Auswahlzwischen verschiedenen Figuren haben soll. Um das zu ermoglichenmuss dass System zwischen zwei

”Zustanden“ unterscheiden

konnen:

I Auswahl einer Spielfigur

I Spielen des eigentlichen Levels

Wahrend des Spielens treten drei (bzw. vier) Unterzustande auf:

I (Spiel ist in einem undefinierten Zustand)

I Spiel wird ausgefuhrt

I Spieler hat gewonnen

I Spieler hat verloren

Page 100: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Modi

Page 101: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Modi

Page 102: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Intent

Allow an object to alter its behaviour when its internal statechanges. The object will appear to change its class.

Also Known As

Objects for States

Movivation

[TCP-connection object. We use Streams as simpler example.]

Page 103: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Page 104: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Page 105: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Applicability

Use the State pattern in either of the following cases:

I An object’s behavior depends on its state, and it must changeits behavior at run-time depending on that state.

I Operations have large, multipart conditional statements thatdepend on the object’s state. This state is usually representedby one or more enumerated constants. Often, severaloperations will contain this same conditional structure. TheState pattern puts each branch of the conditional in a separateclass. This lets you treat the object’s state as an object in itsown right that can vary independently from other objects.

Page 106: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Structure

ConcreteStateA

handle() handle()

ConcreteStateB

Context

request()state.handle();

State

handle()

state

1

...

Page 107: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Participants

I ContextI defines the interface of interest to clientsI maintains an instance of a ConcreteState subclass that defines

the current state.

I StateI defines an interface for encapsulating the behavior associated

with a particular state of the Context

I ConcreteState subclassesI each subclass implements a behavior associated with a state of

the Context

Page 108: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Collaborations

I Context delegates state-specific requests to the currentConcreteState object

I A context may pass itself as an argument to the State objecthandling the request. This lets the State object access thecontext if necessary

I Context is the primary interface for clients. Clients canconfigure a context with State objects. Once a context isconfigured, its clients don’t have to deal with the Stateobjects directly

I Either Context or the ConcreteState subclasses can decidewhich state succeeds another and under what circumstances.

Page 109: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Consequences

The State pattern has the following consequences:

I It localizes state-specific behavior and partitions behavior fordifferent states.

I It makes state transitions explicit

I State objects can be shared

Page 110: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State (Behavioral Pattern)

Implementation and Sample Code . . .

Known Uses

Realization of state diagrams by state objects.

Related Patterns

The Flyweight (195) pattern explains when and how State objectscan be shared.

State objects are often Singletons (127).

Page 111: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

Page 112: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

Page 113: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

class MyStream

{

MyStream(Pathname Pathname = Pathname::NoPathname,

bool TryToOpen = false)

: _Pathname{ Pathname }

{

Super();

if (TryToOpen)

{

Format("Opening stream %s during construction.",

stream);

Open();

}

}

...

Page 114: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

...

private Pathname _Pathname;

virtual bool Open()

{

if (_Pathname.Exists())

{

ChangeClass(OpenStream::GetClass());

return true;

}

else

{

return false;

}

}

...

Page 115: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

...

virtual void Close()

{

ChangeClass(ClosedStream::GetClass());

}

...

Page 116: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

...

virtual void Write(String Text)

{

Format("Trying to open stream before writing.");

if (Open())

{

// Note that this now a call to

// OpenStream::Write()!

Write(Text);

}

else

{

Warn("Cannot write to %s", this);

}

}

};

Page 117: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

class OpenStream : public Stream

{

virtual bool Open() {}; // Do nothing.

virtual void Write(String Text)

{

Format("Writing to stream: %s", Text);

}

};

Page 118: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

class ClosedStream : public Stream

{

virtual void Close() {}; // Do nothing.

virtual void Write(String Text)

{

Format("Cannot write to closed stream.");

}

};

Page 119: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

void TestStreamWriting(Stream Stream)

{

Format("Stream: %s.", Stream);

Stream->Write("Hello!");

Format("Stream: %s.", Stream);

Stream->Close();

Format("Stream: %s.", Stream);

Stream->Write("Goodbye!");

}

Page 120: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

int main()

{

TestStreamWriting(new Stream());

TestStreamWriting(new Stream("a-file-that-exists"));

TestStreamWriting(new Stream("a-file-that-exists",

true));

...

Page 121: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

Stream: #<MY-STREAM {1002CDAC93}>.

Trying to open stream before writing.

WARNING: Cannot write to #<MY-STREAM {1002CDAC93}>.

Stream: #<MY-STREAM {1002CDAC93}>.

Stream: #<CLOSED-STREAM {1002CDAC93}>.

Cannot write to closed stream.

Page 122: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

Stream: #<MY-STREAM {1002E758A3}>.

Trying to open stream before writing.

Writing to stream: Hello!

Stream: #<OPEN-STREAM {1002E758A3}>.

Stream: #<CLOSED-STREAM {1002E758A3}>.

Cannot write to closed stream.

Page 123: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

Opening stream #<MY-STREAM {1002EE3213}>

during construction.

Stream: #<OPEN-STREAM {1002EE3213}>.

Writing to stream: Hello!

Stream: #<OPEN-STREAM {1002EE3213}>.

Stream: #<CLOSED-STREAM {1002EE3213}>.

Cannot write to closed stream.

Page 124: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

...

Stream::MyStream(Pathname Pathname = Pathname::NoPathname,

bool TryToOpen = true)

: _Pathname{ Pathname }

{

Super();

if (TryToOpen)

{

Format("Opening stream %s during construction.",

stream);

Open();

}

}

TestStreamWriting(new Stream("a-file-that-exists",

true));

}

Page 125: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

Opening stream #<MY-STREAM {1002F4DB43}>

during construction.

Stream: #<OPEN-STREAM {1002F4DB43}>.

Writing to stream: Hello!

Stream: #<OPEN-STREAM {1002F4DB43}>.

Stream: #<CLOSED-STREAM {1002F4DB43}>.

Cannot write to closed stream.

Page 126: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defclass my-stream ()

((stream-pathname :accessor stream-pathname

:initarg :pathname :initform nil)))

(defgeneric open-my-stream (stream))

(defmethod open-my-stream ((stream my-stream))

(if (and (pathnamep (stream-pathname stream))

(probe-file (stream-pathname stream)))

(progn

(change-class stream ’open-stream)

t)

nil))

Page 127: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defmethod initialize-instance :after

((stream my-stream) &key try-to-open)

(when try-to-open

(format *standard-output*

"Opening stream ~A during construction."

stream)

(open-my-stream stream)))

Page 128: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defgeneric close-my-stream (stream))

(defmethod close-my-stream ((stream my-stream))

(change-class stream ’closed-stream))

Page 129: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defgeneric write-to-my-stream (stream text))

(defmethod write-to-my-stream ((stream my-stream) text)

(format *standard-output*

"~&Trying to open stream before writing.")

(if (open-my-stream stream)

(write-to-my-stream stream text)

(warn "Cannot write to ~A." stream)))

Page 130: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defclass open-stream (my-stream)

())

(defmethod open-my-stream ((stream open-stream))

;; do nothing

nil)

(defmethod write-to-my-stream ((stream open-stream) text)

(format *standard-output*

"~&Writing to stream: ~A" text))

Page 131: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defclass closed-stream (my-stream)

())

(defmethod close-my-stream ((stream closed-stream))

;; do nothing

nil)

(defmethod write-to-my-stream ((stream closed-stream) text)

(format *standard-output*

"~&Cannot write to closed stream."))

Page 132: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defun test-stream-writing (stream)

(format *standard-output* "~&Stream: ~A." stream)

(write-to-my-stream stream "Hello!")

(format *standard-output* "~&Stream: ~A." stream)

(close-my-stream stream)

(format *standard-output* "~&Stream: ~A." stream)

(write-to-my-stream stream "Goodbye!")

(format *standard-output* "~2%"))

Page 133: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(test-stream-writing

(make-instance ’my-stream))

(test-stream-writing

(make-instance ’my-stream

:pathname #P"change-class.lisp"))

(test-stream-writing

(make-instance ’my-stream

:pathname #P"change-class.lisp"

:try-to-open t))

Page 134: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

State Pattern und Reflection

(defmethod initialize-instance :after

((stream my-stream) &key (try-to-open t))

(when try-to-open

(format *standard-output*

"Opening stream ~A during construction."

stream)

(open-my-stream stream)))

(test-stream-writing

(make-instance ’my-stream

:pathname #P"change-class.lisp"))

Page 135: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

Problem

Wie kann ich einen generischen Mechanismus schaffen, der esEntwicklern oder Anwendern erlaubt Anwendungsobjekte zuerzeugen oder zu konfigurieren?

Mogliche Losung

Zugriff mittels Reflection.

Page 136: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

(defgeneric print-info (object))

(defmethod print-info :before (object)

(format t "~&Object has type ~A."

(class-name (class-of object)))

(format t "~&Its superclasses are ~A."

(mapcar ’class-name

(class-superclasses (class-of object)))))

(defmethod print-info (object)

(format t "~&Its value is ~A.~2%" object))

Page 137: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

(defmethod print-info ((object standard-object))

(dolist (slot (mop::class-slots (class-of object)))

(let ((name (mop::slot-definition-name slot)))

(format t "~&Slot ~A has value ~A."

name

(slot-value object name))))

(format t "~2%"))

Page 138: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

(defclass my-class ()

((slot-a :initform 10 :initarg :a)

(slot-b :initform 20 :initarg :b)))

(defclass your-class (my-class)

((slot-c :initform 30 :initarg :c)))

(defclass another-class ()

((just-one-slot :initform "Foo")))

(defclass a-fancy-class (your-class another-class)

((and-yet-another-slot :initform "Bar")))

Page 139: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

(print-info (make-instance ’my-class))

(print-info (make-instance ’my-class :a 1 :b 99))

(print-info (make-instance ’your-class))

(print-info (make-instance ’another-class))

(print-info (make-instance ’a-fancy-class))

(print-info 123)

(print-info "Foo")

Page 140: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

Object has type MY-CLASS.

Its superclasses are (MY-CLASS STANDARD-OBJECT).

Slot SLOT-A has value 10.

Slot SLOT-B has value 20.

Object has type MY-CLASS.

Its superclasses are (MY-CLASS STANDARD-OBJECT).

Slot SLOT-A has value 1.

Slot SLOT-B has value 99.

Object has type YOUR-CLASS.

Its superclasses are (YOUR-CLASS MY-CLASS STANDARD-OBJECT).

Slot SLOT-A has value 10.

Slot SLOT-B has value 20.

Slot SLOT-C has value 30.

Page 141: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

Object has type ANOTHER-CLASS.

Its superclasses are (ANOTHER-CLASS STANDARD-OBJECT).

Slot JUST-ONE-SLOT has value Foo.

Object has type A-FANCY-CLASS.

Its superclasses are (A-FANCY-CLASS YOUR-CLASS

ANOTHER-CLASS MY-CLASS

STANDARD-OBJECT).

Slot JUST-ONE-SLOT has value Foo.

Slot SLOT-A has value 10.

Slot SLOT-B has value 20.

Slot SLOT-C has value 30.

Slot AND-YET-ANOTHER-SLOT has value Bar.

Page 142: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

Object has type FIXNUM.

Its superclasses are (FIXNUM INTEGER RATIONAL

REAL NUMBER T).

Its value is 123.

Object has type SIMPLE-CHARACTER-STRING.

Its superclasses are (SIMPLE-CHARACTER-STRING

CHARACTER-STRING SIMPLE-STRING

STRING VECTOR SEQUENCE

SIMPLE-ARRAY ARRAY T).

Its value is Foo.

Page 143: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

UPROPERTY(EditAnywhere, BlueprintReadWrite,

Category = "Spawning")

float SpawnDelayRangeLow;

UPROPERTY(EditAnywhere, BlueprintReadWrite,

Category = "Spawning")

float SpawnDelayRangeHigh;

UPROPERTY(EditAnywhere, BlueprintReadWrite,

Instanced, Category = "Spawning")

UPickupFactory* PickupFactory;

Page 144: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

UCLASS(Abstract, Blueprintable, EditInlineNew)

class PG_API UPickupFactory : public UObject

{ ... }

UCLASS(AutoExpandCategories = "Spawning")

class PG_API UTwoPickupTypesFactory

: public UPickupFactory

{ ... }

Page 145: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Reflection: Visualisierung von Objekten

Page 146: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Spielerfiguren

I Wir haben jetzt die Moglichkeit geschaffen, dass Spielerverschiedene Spielerfiguren auswahlen konnen

I Diese Figuren sollen auch unterschiedlich auf die einzelnenBonusitems reagieren

I Im Moment wird der Effekt, den ein Bonusitem auf dieSpielerfigur hat vom Bonusitem selber bestimmt. Das ist nichtflexibel genug

I Zusatzlich soll es moglich sein, wahrend des Spiels dieReaktion auf Bonusitems zu verandern (Power-Ups,Malus-Items)

Page 147: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Spielerfiguren

Mogliche Losung

I Lagere die Reaktion auf Pickups in eine Klassenhierarchie aus,die Handler definiert, die nur fur die Interaktion zwischenFiguren und Bonusitems zustandig sind

I Jeder Handler implementiert nur einen Teil aller moglichenKombinationen

I Wenn ein Handler nicht auf einePickup/Character-Kombination reagieren kann, reicht sie dieArbeit an eine andere Klasse weiter

Page 148: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Chain of Responsibility (Behavioral Pattern)

Intent

Avoid coupling the sender of a request to its receiver by givingmore than one object a chance to handle the request. Chain thereceiving objects and pass the request along the chain until anobject handles it.

Motivation

Consider a context-sensitive help facility for a graphical userinterface. The user can obtain help information on any part of theinterface just by clicking on it. [. . . ]

Page 149: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Chain of Responsibility (Behavioral Pattern)

Applicability

Use Chain of Responsibility when

I More than one object may handle a request, and the handlerisn’t known a priori. The handler should be ascertainedautomatically

I You want to issue a request to one of several objects withoutspecifying the receiver explicitly

I The set of objects that can handle a request should bespecified dynamically

Page 150: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Chain of Responsibility (Behavioral Pattern)

Structure

Page 151: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Chain of Responsibility (Behavioral Pattern)

Participants

I HandlerI defines an interface for handling requestsI (optional) implements the successor link

I ConcreteHandlerI handles requests it is responsible for.I can access its successor.I if the ConcreteHandler can handle the request, it does so;

otherwise it forwards the request to its successor.

I ClientI initiates the request to a ConcreteHandler object on the chain.

Collaborations

When a client issues a request, the request propagates along thechain until a ConcreteHandler object takes responsibility forhandling it.

Page 152: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Chain of Responsibility (Behavioral Pattern)

Consequences

Chain of Responsibility has the following benefits and liabilities:

I Reduced coupling. The pattern frees an object from knowingwhich other object handles a request. [. . . ] As a result, Chainof Responsibility can simplify object interconnections. [. . . ]

I Added flexibility in assigning responsibilities to objects. [. . . ]You can add or change responsibilities for handling a requestby adding to or otherwise changing the chain at run-time. Youcan combine this with subclassing to specialize handlersstatically.

I Receipt isn’t guaranteed. Since a request has no explicitreceiver, there’s no guarantee it’ll be handled—the requestcan fall off the end of the chain without ever being handled. Arequest can also go unhandled when the chain is notconfigured properly.

Page 153: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Chain of Responsibility (Behavioral Pattern)

Related Patterns

Chain of Responsibility is often applied in conjunction withComposite (163). There, a component’s parent can act as itssuccessor.

Page 154: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Spielerfiguren

I Chain of Responsibility lost die Anforderungen, die am Beginnder Aufgabenstellung genannt wurden.

I Die Kette an Nachfolger-Handlern ermoglicht es, leicht neueVerhalten einzufuhren

I Aber: Die verkettete Struktur der Nachfolger-Handlererschwert die Konfiguration der Handler fur dieSpiele-Designer

I Daher: Verwendung von Handlern ohne Verkettung; der Clientruft die Handler explizit der Reihe nach auf

I Handler geben Boole’schen Wert zuruck, der angibt ob sie diedie Aufgabe bearbeitet haben

Page 155: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Spielerfiguren

Page 156: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Verschiedene Spielerfiguren

Bemerkung

Wir hatten ursprunglich die Reaktion der Spielfigur auf Pickupsdirekt in der Klasse APGCharacter implementiert. Ware das nichtausreichend gewesen?

Das war aus mehreren Grunden kein besonders gutes Design:

I Jede Art von Spielfigur muss die Reaktion auf allePickup-Typen selber implementieren. Wir wollen dieMoglichkeit haben, gemeinsame Verhalten wieder zuverwenden.

I Die Anderung des Verhaltens zur Laufzeit ist schwierig undmuss fur jede Art von Figur gesondert implementiert werden.

Page 157: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Benutzeroberflache

I Komponenten in der Benutzeroberflache haben einehierarchische Struktur:

I BildschirmI FensterI EingabemaskeI Eingabefeld, Button, etc.

I Das Interface der Komponenten soll einheitlich sein

Page 158: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Composite (Structural Pattern)

Intent

Compose objects into tree structures to represent part-wholehierarchies. Composite lets clients treat individual objects andcompositions of objects uniformly.

Motivation

Graphical editors let users build complex diagrams from simplercomponents. Components can be grouped to form largercomponents, which can themselves be grouped to form even largercomponents. Code that uses these components should not have todistinguish between primitives and complex components. TheComposite pattern describes how to use recursive composition sothat clients don’t have to make this distinction.

Page 159: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Composite (Structural Pattern)

Applicability

Use the Composite pattern when

I You want to represent part-whole hierarchies of objects.

I You want clients to be able to ignore the difference betweencompositions of objects and individual objects. Clients willtreat all objects in the composite structure uniformly.

Page 160: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Composite (Structural Pattern)

Structure

Page 161: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Composite (Structural Pattern)

Consequences

The Composite pattern

I defines class hierarchies consisting of primitive and compositeobjects

I makes the clients simple

I makes it easier to add new kinds of components

I can make your design overly general

Page 162: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Composite (Structural Pattern)

Known uses Composite and Control in SWT, abstract syntaxtrees in compilers, . . .

Related Patterns

I Chain of Command

I Decorator

I Iterator

I Visitor

I . . .

Example . . .

Page 163: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Designproblem: Unabhangige Item-Erzeuger

I Bevor das Spiel startet und nach dem Ende des Spiels sollenalle Item-Erzeuger angehalten werden.

I Der Stand des Spiels wird von einer Instanz der KlasseUGameMode verwaltet

I UGameMode soll nichts uber Item-Erzeuger wissen, sondernnur die Transitionen zwischen Spiel aktiv/gewonnen/verlorenverwalten

I APickup soll nichts uber die Funktionalitat von UGameModewissen

Page 164: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Intent

Define a one-to-many dependency between objects so that whenone object changes state, all its dependents are notified andupdated automatically.

Motivation

When partitioning a system into collaborating classes it is oftennecessary to maintain consistency between related objects. Wedon’t want to have tight coupling between these classes. TheObserver pattern describes how a subject may have any number ofobservers that are kept update about changes to the subject.

Page 165: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Applicability

Use the Observer pattern when

I An abstraction has two aspects and one of them depends onthe other.

I When a change in one object causes change in several othersand you don’t know exactly how many or which ones.

I When an Object needs to notify other objects without makingassumptions what these objects are.

Page 166: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Structure

for all o in observers doo.update();

ConcreteObserver

observerStateobserverState = subject.getState();

Observer

update()

update()

subjectState

return subjectState;getState()

attach(o: Observer)

detach(o: Observer)

notify()

Subject*

observers

subject

1ConcreteSubject

setState()

Page 167: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Participants

I SubjectI knows its observers. Any number of Observer objects may

observe a subjectI provides an interface for attaching and detaching Observer

objects

I ObserverI defines an updating interface for objects that should be

notified of changes in a subject

I ConcreteSubjectI stores state of interest to ConcreteObserver objectsI sends a notification to its observers when its state changes

I ConcreteObserverI maintains a reference to a ConcreteSubject objectI stores state that should stay consistent with the subject’sI implements the Observer updating interface to keep its state

consistent with the subject’s

Page 168: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Collaborations

I ConcreteSubject notifies its observers whenever a changeoccurs that could make its observers’ state inconsistent withits own.

I After being informed of a change in the concrete subject, aConcreteObserver object may query the subject forinformation. ConcreteObserver uses this information toreconcile its state with that of the subject.

Page 169: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

notify()

:AConcreteSubject:AConcreteObserver :AnotherConcreteObserver

setState()

update()

update()

getState()

getState()

Page 170: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Consequences

The Observer pattern lets you vary subjects and observersindependently. You can reuse subjects without reusing theirobservers, and vice versa. It lets you add observers withoutmodifying the subject or other observers. Further benefits andliabilities of the Observer pattern include the following:

I Abstract coupling between Subject and Observer [. . . ]

I Support for broadcast communication [. . . ]

I Unexpected updates [. . . ]

Page 171: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Observer (Behavioral Pattern)

Known uses

Event listeners in user interfaces (SWT)

Related Patterns

I Mediator (273): By encapsulating complex update semantics,the ChangeManager acts as mediator between subjects andobservers

I Singleton (127): The ChangeManager [in a variantimplementation of the pattern] may use the Singleton patternto make it unique and globally accessible

Page 172: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Proxy (Structural Pattern)

Intent

Provide a surrogate or placeholder for another object to controlaccess to it.

Structure

Page 173: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Iterator (Behaviorual Pattern)

Intent

Provide a way to access the elements of an aggregate objectsequentially without exposing its underlying representation.

Structure

Page 174: Entwurfsmuster (Patterns) Prof. Dr. Matthias H olzl Joschka Rinke · Beispiel: Design-Pattern im GoF-Katalog Beschreibungsform f ur Design Pattern I Pattern Name and Classi cation

Zusammenfassung

I Ein Entwurfsmuster liefert eine generische Beschreibung einerbewahrten Losung fur eine wiederkehrende Problemklasse.

I Die Beschreibung eines Entwurfsmuster erfolgt in einerstrukturierten Form, die aus verschiedenen Elementen besteht(Name des Musters, Zweck, Anwendbarkeit, Losungsstruktur,...)

I Im Design-Pattern Katalog von Gamma et al. werden 23objektorientierte Pattern beschrieben.

I Diese Pattern sind nach den Gesichtspunkten”Creational“

(z.B. Abstract Factory),”Structural“ (z.B. Composite) und

”Behavioral“ (z.B. State, Observer) klassifiziert.


Recommended