1 / 145

CS352 – Software Engineering II Lecture 9,11,12, 13, 14,15, 16 : Design Patterns

CS352 – Software Engineering II Lecture 9,11,12, 13, 14,15, 16 : Design Patterns. Overview of This Lecture. Design Patterns: Introduction to SW Design Patterns Player-role Pattern State Pattern Strategy Pattern Java GUI Model Adapter Pattern Command Pattern.

edelacruz
Download Presentation

CS352 – Software Engineering II Lecture 9,11,12, 13, 14,15, 16 : Design Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS352 – Software Engineering IILecture 9,11,12, 13, 14,15,16: Design Patterns

  2. Overview of This Lecture • Design Patterns: • Introduction to SW Design Patterns • Player-role Pattern • State Pattern • Strategy Pattern • Java GUI Model • Adapter Pattern • Command Pattern

  3. Design Pattern: Introduction • There are recurring/characteristic problems during a design activity. • E.g., A certain class should have only one instance. • Known as Pattern. • Designers come up with various solutions to deal with these problems. • Eventually, best known solutions are collected and documented as DesignPatterns.

  4. Design Pattern: Definition • A Design Pattern is the outline of a reusablesolutionto a general problem encountered in a particular context: • describes a recurring problem • describes the core of the solution to that problem. • Design Patterns are namedto facilitate people using and discussing them.

  5. Design Pattern: Usefulness 1.Reuse existing, high-quality solutionsto recurring design problems. 2.Improve future design: Solutions to new problems can be obtained with higher quality. 3. Shift the level of thinking to a higher perspective. 4. Use commonterminology to improve communicationswithin team members. 5.Improvedocumentation: smaller, simpler. 6. Use a rightdesign, not just one that works. 7. Studying patterns is an effective way to learn from the experience of others.

  6. Pattern Categories • Gamma, Helm, Johnson, Vlissides: (Gang of Four, 1995) presented 23design patterns in 3 categories: 1. Creational: Creation of objects. Separate the operations of an application from how its objects are created. 2. Structural: Concern about the composition of objects into larger structures. To provide the possibility of future extension in structure. 3. Behavioral: Define how objects interact and how responsibility is distributed among them. Use inheritance to spread behavior across the subclasses, or aggregation and composition to build complex behavior from simpler components.

  7. GoF: Design Patterns Creational: Abstract Factory Builder Factory Method Prototype Singleton Structural: Adapter Bridge Composite Decorator Façade Flyweight Proxy Behavioral: Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State / Player-role Strategy Template Method Visitor

  8. Pattern Description Format • Context: • The general situation in which the pattern applies. • Problem: • The main difficulty to be tackled. • Criteria for a good solution. • Solution: • Recommended way to solve the problem. • Antipattern (optional): • Erroneous or inferior solution.

  9. 1- The Player-Role Pattern • Context: • A role is a particular set of properties associated with an object in a particular context. An object may playdifferentroles in different contexts. • Example: • A Studentcan be either part time or full time, and can change from one to another. • Problem: • Find the best way to model players and roles so that a player can change roles or possess multiple roles. • We want to avoid multiple inheritance. • We cannot allow an instance to change class.

  10. Player-Role • Solution: • Create a class <<Player>> to represent objects that play roles. • Create an association from this class to an abstract <<Role>> class, a super-class of all possible roles. • Subclasses of <<Role>> encapsulate the properties and behaviors with different roles. • Multiplicity can be one-to-one or one-to-many.

  11. <<AbstractRole>> <<Player>> <<Role1>> <<Role2>> Student AttendanceRole FullTime PartTime The Player-Role Pattern • Solution: General Idea Applied to the student example.

  12. Student • role : int • + method () Student FullTime PartTime Anti Player-Role Pattern { if (role == 1) …. } • Inferior (not so good) Solution: Put role as an attribute Inherit from Student Class

  13. A Player Can Have Multiple Roles StudyLevel Student AttendanceRole Undergrad Postgrad NotRegistered FullTime PartTime

  14. 2. The State Pattern • Context: • An object exhibits different behavior. When its internal state changes, the object appears to have changed its class at run time. • Problem: • Allow different behaviors without actually changing the class of an object. • State changing should be decided by the current behavior. • Should allow only one behavior at any time.

  15. The State Pattern. Solution • There are applications that request an object to alter its behaviour when its internal state changes, e.g., if a class is described by a state-chart. • Solution: represent each state by a separate class. • each state class will implement the appropriate behaviour for each operation in that state only. • A consequence of this pattern is that the state classes need access to the internal details of the context class.

  16. 1 <<Class>> <<AbstractState>> state request( ) handle( ) <<State1>> <<State2>> handle( ) handle( ) 1 CDPlayer CDPlayerStates myState play( ) play( ) Opened Playing Close play( ) play( ) play( ) The State Pattern • Solution: General Idea: { state.handle( ); } Applied to the CD Player Example. { myState.play( ); }

  17. Example – TCPConnection class • A TCPConnection object can be in one of several different states, established, listening or closed. • The behavior of TCPConnection is different in each of these three states.

  18. Example – TCPConnection class TCPState TCPConnection Open() Close() Acknowledge() Open() Close() Acknowledge() state->Open() TCPEstablished TCPListen TCPClosed Open() Close() Acknowledge() Open() Close() Acknowledge() Open() Close() Acknowledge()

  19. Example – TCPConnection class • TCPConnection maintains a state object which is a subclass of TCPState. • When the connection changes state the TCPConnection object changes the state object it uses.

  20. CDPlayer myState play( ) The State Pattern • Antipattern: • Code all the behaviors in one class, and make use of if-then-else or switch to decide what is the correct response. { if (myState == OPEN) ... else if (myState == CLOSED) ... else if (myState == PLAYING) ... }

  21. Comparison: Player-Role and State Patterns • Similarities: • <<Player>> is replaced by <<Class>> • <<AbstractRole>> is replaced by <<AbstractState>> • <<State1>>, … are replaced by <<Role1>>, … • Differences: • The change of <<Role>> is decided by the <<Player>> instead of depending on the <<Role>>; • The change of <<State>> is decided by the <<State>>. • Hence it is a two-ways relation and a state needs to have a link to its class to be able to change its state

  22. 3. The Strategy Pattern • Context: • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. • Problem: • Allow different behaviors without actually changing the class of an object. • Strategy / Algorithm change as needed within the same class

  23. The Strategy Pattern. Solution • Solution: represent each strategy by a separate class. • each strategy class will implement the appropriate algorithm • At run time, a class can change its strategy

  24. The Strategy Pattern • Solution:

  25. The Strategy Pattern: Applicability • Many related classes differ only in behavior • You need different variants of an algorithm • An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures. • A class defines many behaviors, and these appear as multiple conditional statements in its operations. • Instead of many conditionals, move related branches into their own Strategy class

  26. The Strategy Pattern: Example • Solution:

  27. Example – Java GUI • Solution:

  28. Example – Java GUI • Situation: A GUI container object wants to decide at run-time what strategy it should use to layout the GUI components it contains. • Many different layout strategies are already available. • Solution: Encapsulate the different layout strategies using the Strategy pattern! • This is what the Java AWT does with its Layout Managers!

  29. Example – Java GUI • Sample Code: • Frame f = new Frame(); • f.setLayout(new FlowLayout()); • f.add(new Button(“Press”)); • http://docs.oracle.com/javase/tutorial/uiswing/layout/

  30. 4. Adapter Pattern

  31. 4. Adapter Pattern • Context: • A legacy class or piece of software has an old interface. The client is expecting to use a newinterface. • Adapter allows the client to use the legacy class easily. • Problem: • Incompatible interfaces of two pieces of software, one of them must use the other.

  32. Intent • Convert the interface of a class into another interface clients expect. • Adapter lets classes work together, that could not otherwise because of incompatible interfaces. • Wrap an existing class with a new interface. • Also Known As -> Wrapper

  33. Motivation • Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application • We can not change the library interface, since we may not have its source code • Even if we did have the source code, we probably should not change the library for each domain-specific application

  34. Implementation

  35. Implementation • Target - defines the domain-specific interface that Client uses. • Adapter - adapts the interface Adaptee to the Target interface. • Adaptee - defines an existing interface that needs adapting. • Client - collaborates with objects conforming to the Target interface.

  36. ? Example 1 • Java Wrapper Classes • Integer • Double • Character • …………….. • asList () to wrap an array as a list • Arrays.asList()

  37. Example 2 • Java Vector class • Enumeration<E> elements()returns an enumeration of the components of this vector. • public interface Enumeration<E> • An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series. For example, to print all elements of a Vector<E> v: • for (Enumeration<E> e = v.elements(); e.hasMoreElements();) System.out.println(e.nextElement());

  38. Enumeration vs. Iterator

  39. Example 2 – Possible Solution from Stackoverflow.com • No need to reinvent the wheel. Just use Collections.list(Enumeration<T> e), which returns an ArrayList<T>. Then use ArrayList.iterator() to get an Iterator. • This is not ideal though, since we then have to construct an ArrayList each time we want to iterate. This can be expensive, especially with a large Collection.

  40. Example 2 – Solution: Create an AdapterClass Diagram for the IterableEnumeration See Code IteratorEnumeration

  41. 5. Command Pattern • The command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

  42. Intent • Encapsulate a request in an object • Allows the parameterization of clients with different requests • Allows saving the requests in a queue

  43. 5. Command Pattern • Context: • Sometimes it’s necessary to issue requests to objectswithoutknowing anything about the operation being requested or the receiver of the request. • Like impl. of buttons, menus in user interface toolkits. • Problem: • We do not wan to tie the invoker (making the request) to the actual object that will execute the request.

  44. The Strategy Pattern. Solution • The Command pattern lets toolkit objects make requests of unspecified application objects by turning the request itself into an object.

More Related