Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 1 Q3: common mistakes Dashed lines for data flow &

Similar presentations


Presentation on theme: "Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 1 Q3: common mistakes Dashed lines for data flow &"— Presentation transcript:

1 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 1 Q3: common mistakes Dashed lines for data flow & object creation Creation of extra objects c2, c3, … etc. Treating int data types as if they are objects Missing messages Usually getVal() is omitted Incorrect directions and/or related objects of messages Missing last data flow from a:A (return i*2) The values on the data flows (5 and 10) Do not write “return” Order of events garbled Missing inactivity lines and/or activity boxes Fibonacci Some people wrote Fibonacci, with no hints how they got that result (no code traces anywhere)

2 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 2 Q3 a:A b:B c:C method1(b) create() methodB(_c,5) setSeed(5) calcVal(5) getVal() 5 10 public class A{ int method1(B _b){ C _c = new C(); _b.methodB(_c, 5); int i = _c.getVal(); return i * 2; } public class B{ int methodB(C _c2, int s){ _c2.setSeed(s); _c2.calcVal(); } public class C{ private int mySeed; private int myVal; void setSeed(int i){ this.mySeed = i; } void calcVal(void){ int a=0, b=1; for(int i=0;i<mySeed;i++){ a = a+b; b = a-b; } myVal = a; } int getVal(void){ return myVal; }

3 Chapter 8, Object Design: Design Patterns II Using UML, Patterns, and Java Object-Oriented Software Engineering

4 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 4 Review: Design pattern A design pattern is… …a template solution to a recurring design problem Look before re-inventing the wheel just one more time …reusable design knowledge Higher level than classes or datastructures (link lists,binary trees...) Lower level than application frameworks …an example of modifiable design Learning to design starts by studying other designs

5 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 5 Why are modifiable designs important? A modifiable design enables… …an iterative and incremental development cycle concurrent development risk management flexibility to change …to minimize the introduction of new problems when fixing old ones …to deliver more functionality after initial delivery

6 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 6 What makes a design modifiable? Low coupling and high cohesion Clear dependencies Explicit assumptions How do design patterns help? They are generalized from existing systems They provide a shared vocabulary to designers They provide examples of modifiable designs Abstract classes Delegation

7 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 7 A Taxonomy of Design Patterns

8 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 8 On to More Patterns! Structural pattern Proxy Creational Patterns Abstract Factory Builder Behavioral pattern Command Observer Strategy

9 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 9 Proxy Pattern What is expensive? Object Creation Object Initialization Defer object creation and object initialization to the time you need the object Proxy pattern: Reduces the cost of accessing objects Uses another object (“the proxy”) that acts as a stand-in for the real object The proxy creates the real object only if the user asks for it

10 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 10 The Proxy Pattern: 3 Types Caching of information (“Remote Proxy”) The Proxy object is a local representative for an object in a different address space Good if information does not change too often Standin (“Virtual Proxy”) Object is too expensive to create or too expensive to download. Good if the real object is not accessed too often Example: RealImage and ImageProxy Access control (“Protection Proxy”) The proxy object provides protection for the real object Good when different actors should have different access and viewing rights for the same object Example: Grade information accessed by administrators, teachers and students.

11 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 11 Virtual Proxy example Images are stored and loaded separately from text If a RealImage is not loaded a ProxyImage displays a grey rectangle in place of the image The client cannot tell that it is dealing with a ProxyImage instead of a RealImage A proxy pattern can be easily combined with a Bridge Image boundingBox() draw() realSubject RealImage boundingBox() draw() ProxyImage boundingBox() draw()

12 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 12 Before

13 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 13 Controlling Access

14 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 14 After

15 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 15 Command Pattern: Motivation You want to build a user interface You want to provide menus You want to make the menus reusable across many applications The applications only know what has to be done when a command from the menu is selected You don’t want to hardcode the menu commands for the various applications Such a user interface can easily be implemented with the Command Pattern.

16 Command Pattern Client (in this case a user interface builder) creates a ConcreteCommand (strings like “commit”, “execute”, “undo”) and binds it to an action operation in Receiver Client hands the ConcreteCommand over to the Invoker which stores it (for example in a menu) The Invoker has the responsibility to execute or undo a command (based on a string entered by the user) Command execute() Receiver action1() action2() Client Invoker (application) ConcreteCommand1 execute() «binds» ConcreteCommand2 execute() «binds»

17 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 17 Comments to the Command Pattern The Command abstract class declares the interface supported by all ConcreteCommands. The client is a class in a user interface builder or in a class executing during startup of the application to build the user interface. The client creates ConcreteCommands and binds them to specific Receivers, this can be strings like “commit”, “execute”, “undo”. So all user-visible commands are sub classes of the Command abstract class. The invoker - the class in the application program offering the menu of commands or buttons - invokes the ConcreteCommand based on the string entered and the binding between action and ConcreteCommand.

18 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 18 Decouples boundary objects from control objects The command pattern can be nicely used to decouple boundary objects from control objects: Boundary objects such as menu items and buttons, send messages to the command objects (I.e. the control objects) Only the command objects modify entity objects When the user interface is changed (for example, a menu bar is replaced by a tool bar), only the boundary objects are modified.

19 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 19 Command Pattern Applicability Parameterize clients with different requests Queue or log requests Support undoable operations Uses: Undo queues Database transaction buffering

20 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 20 Applying the Command Pattern to Command Sets GameBoard «binds» TicTacToeMove execute() ChessMove execute() Move execute() Match * replay() play()

21 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 21 Applying the Command design pattern to Replay Matches in ARENA replay() «binds» play() TicTacToeMoveChessMove Move execute() Match * GameBoard nextMove() ReplayedMatch previousMove()

22 Observer Pattern Motivation Problem: We have an object that changes its state quite often Example: A Portfolio of stocks We want to provide multiple views of the current state of the portfolio Example:Histogram view, pie chart view, time line view, alarm Requirements: The system should maintain consistency across the (redundant) views, whenever the state of the observed object changes The system design should be highly extensible It should be possible to add new views without having to recompile the observed object or the existing views. Portfolio Stock *

23 Observer Pattern: Decouples an Abstraction from its Views Subject subscribe(subscriber) unsubscribe(subscriber) notify() The Subject (“Publisher”) represents the entity object Observers (“Subscribers”) attach to the Subject by calling subscribe() Each Observer has a different view of the state of the entity object The state is contained in the subclass ConcreteSubject The state can be obtained and set by subclasses of type ConcreteObserver. update() Observer *observers ConcreteSubject state getState() setState() ConcreteObserver observeState update()

24 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 24 Observer Pattern Models a 1-to-many dependency between objects Connects the state of an observed object, the subject with many observing objects, the observers Usage: Maintaining consistency across redundant states Optimizing a batch of changes to maintain consistency Three variants for maintaining the consistency: Push Notification: Every time the state of the subject changes, all the observers are notified of the change Push-Update Notification: The subject also sends the state that has been changed to the observers Pull Notification: An observer inquires about the state the of the subject Also called Publish and Subscribe.

25 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 25 InfoView update() Observer update() * Subject subscribe() unsubscribe() notify() getState() setState() File -filename ListView update() PowerpointView update() Applying the Observer Pattern to maintain Consistency across Views

26 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 26 Strategy Pattern Different algorithms exists for a specific task We can switch between the algorithms at run time Examples of tasks: Different collision strategies for objects in video games Parsing a set of tokens into an abstract syntax tree (Bottom up, top down) Sorting a list of customers (Bubble sort, mergesort, quicksort) Different algorithms will be appropriate at different times First build, testing the system, delivering the final product If we need a new algorithm, we can add it without disturbing the application or the other algorithms.

27 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 27 Strategy Pattern Context ContextInterface() Strategy AlgorithmInterface * ConcreteStrategyC AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() ConcreteStrategyA AlgorithmInterface() Policy decides which ConcreteStrategy is best in the current Context. Policy

28 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 28 Using a Strategy Pattern to Decide between Algorithms at Runtime Database SelectSortAlgorithm() Sort() * SortInterface Sort() BubbleSort Sort() QuickSort Sort() MergeSort Sort() Policy TimeIsImportant SpaceIsImportant Client

29 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 29 Supporting Multiple implementations of a Network Interface NetworkInterface open() close() send() receive() NetworkConnection send() receive() setNetworkInterface() Application Ethernet open() close() send() receive() WaveLAN open() close() send() receive() UMTS open() close() send() receive() LocationManager Context = {Mobile, Home, Office}

30 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 30 Applicability of Strategy Pattern Many related classes differ only in their behavior. Strategy allows to configure a single class with one of many behaviors Different variants of an algorithm are needed that trade-off space against time. All these variants can be implemented as a class hierarchy of algorithms

31 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 31 Abstract Factory Pattern Motivation Consider a user interface toolkit that supports multiple looks and feel standards for different operating systems: How can you write a single user interface and make it portable across the different look and feel standards for these window managers? Consider a facility management system for an intelligent house that supports different control systems: How can you write a single control system that is independent from the manufacturer?

32 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 32 Abstract Factory Initiation Assocation: Class ConcreteFactory2 initiates the associated classes ProductB2 and ProductA2 AbstractProductA ProductA1 ProductA2 AbstractProductB ProductB1 ProductB2 AbstractFactory CreateProductA CreateProductB Client CreateProductA CreateProductB ConcreteFactory1 CreateProductA CreateProductB ConcreteFactory2

33 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 33 Applicability for Abstract Factory Pattern Independence from Initialization or Representation Manufacturer Independence Constraints on related products Cope with upcoming change

34 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 34 Applying the Abstract Factory Pattern to Games GameMatchTTTMatchChessMatch Chess TicTacToe createMatch() createStats() StatisticsTTTStatsChessStatsTournament createMatch() createStatistics() createMatch() createStats()

35 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 35 Builder Pattern Motivation Conversion of documents Software companies make their money by introducing new formats, forcing users to upgrades But you don’t want to upgrade your software every time there is an update of the format for Word documents Idea: A reader for RTF format Convert RTF to many text formats (EMACS, Framemaker 4.0, Framemaker 5.0, Framemaker 5.5, HTML, SGML, WordPerfect 3.5, WordPerfect 7.0, ….) Problem: The number of conversions is open-ended. Solution Configure the RTF Reader with a “builder” object that specializes in conversions to any known format and can easily be extended to deal with any new format appearing on the market

36 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 36 Builder Pattern Construct() Director For all objects in Structure { Builder->BuildPart() } BuildPart() Builder BuildPart() GetResult() ConcreteBuilderB Represen- tation B BuildPart() GetResult() ConcreteBuilderA Represen- tation A

37 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 37 Example Parse() RTFReader While (t = GetNextToken()) { Switch t.Type { CHAR: builder->ConvertCharacter(t.Char) FONT: bulder->ConvertFont(t.Font) PARA: builder->ConvertParagraph } ConvertCharacter() ConvertFontChange ConvertParagraph() TextConverter ConvertCharacter() ConvertFontChange ConvertParagraph() GetASCIIText() AsciiConverter AsciiText ConvertCharacter() ConvertFontChange ConvertParagraph() GetASCIIText() TexConverter TeXText ConvertCharacter() ConvertFontChange ConvertParagraph() GetASCIIText() HTMLConverter HTMLText

38 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 38 When do you use the Builder Pattern? The creation of a complex product must be independent of the particular parts that make up the product In particular, the creation process should not know about the assembly process (how the parts are put together to make up the product) The creation process must allow different representations for the object that is constructed. Examples: A house with one floor, 3 rooms, 2 hallways, 1 garage and three doors. A skyscraper with 50 floors, 15 offices and 5 hallways on each floor. The office layout varies for each floor.

39 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 39 Clues in Nonfunctional Requirements for the Use of Design Patterns Text: “manufacturer independent”, “device independent”, “must support a family of products” => Abstract Factory Pattern Text: “must interface with an existing object” => Adapter Pattern Text: “must interface to several systems, some of them to be developed in the future”, “ an early prototype must be demonstrated” =>Bridge Pattern Text: “must interface to existing set of objects” => Façade Pattern

40 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 40 Clues in Nonfunctional Requirements for use of Design Patterns (2) Text: “complex structure”, “must have variable depth and width” => Composite Pattern Text: “must be location transparent” => Proxy Pattern Text: “must be extensible”, “must be scalable” => Observer Pattern Text: “must provide a policy independent from the mechanism” => Strategy Pattern

41 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 41 Summary Composite, Adapter, Bridge, Façade, Proxy (Structural Patterns) Focus: Composing objects to form larger structures Realize new functionality from old functionality, Provide flexibility and extensibility Command, Observer, Strategy (Behavioral Patterns) Focus: Algorithms and assignment of responsibilities to objects Avoid tight coupling to a particular solution Abstract Factory, Builder (Creational Patterns) Focus: Creation of complex objects Hide how complex objects are created and put together

42 Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 42 Conclusion Design patterns provide solutions to common problems lead to extensible models and code can be used as is or as examples of interface inheritance and delegation apply the same principles to structure and to behavior Design patterns solve a lot of your software development problems Pattern-oriented development


Download ppt "Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 1 Q3: common mistakes Dashed lines for data flow &"

Similar presentations


Ads by Google