Presentation is loading. Please wait.

Presentation is loading. Please wait.

Design Pattern Detection

Similar presentations


Presentation on theme: "Design Pattern Detection"— Presentation transcript:

1 Design Pattern Detection

2 Design Patterns can be simple…
Highlighting a SHAPE in a GUI application Possible solution: Each class, such as CAR, HOUSE implements a method called highlight Problem: Inconsistent Solution: In class SHAPE: public void highlight(…) { translate(1,1); draw(); translate(-2,-2); } 11/20/2018 COSC6431

3 Template Method 11/20/2018 COSC6431

4 Template Method Context An algorithm is applicable for multiple types
The algorithm can be broken down into primitive operations that may be different for each type The order of the primitive operations does not depend on the type Solution Define an abstract superclass with a method for the algorithm and abstract methods for the primitive operations Algorithm calls primitive operations in right order Each subclass implements primitive operations but not the algorithm 11/20/2018 COSC6431

5 DPs can be language dependent
Singleton pattern: A particular class must have only one instance. This instance may be shared across the system. public class Singleton { // Java private Singleton() {…} public static Singleton getSingleton() { if (instance == null) instance = new Singleton(); return instance; } private static Singleton instance; What about threads? Cloning? 11/20/2018 COSC6431

6 Singleton Pattern in Eiffel
Eiffel has once functions but no static variables * SINGLETON * SINGLETON_ACCESSOR + SINGLE_INSTANCE_CLASS + INSTANCE_ACCESSOR CLIENT 11/20/2018 COSC6431

7 Singleton – Participants
Used to type a class as a singleton Single instance class The class that should have only one instance Singleton accessor Declares access point for a single instance Instance accessor Access point (storage location) for the single instance Client Uses instance accessor to get the single instance 11/20/2018 COSC6431

8 Singleton – Scenario 1 CLIENT INSTANCE_ACCESSOR 2
SINGLE_INSTANCE_CLASS Scenario: Get instance Request the_instance Create the_instance (only once) 11/20/2018 COSC6431

9 Singleton Class deferred class SINGLETON feature {NONE}
the_singleton : SINGLETON is deferred end -- The unique instance of this class -- Should be redefined as a once function -- returning Current in concrete subclasses invariant only_one_instance: Current = the_singleton end Enforces single instance property 11/20/2018 COSC6431

10 Singleton Accessor Class
deferred class SINGLETON_ACCESSOR feature {NONE} singleton : SINGLETON is deferred end -- Access to a unique instance. -- Must be redefined as once function. is_real_singleton : BOOLEAN is do Result := singleton = singleton end invariant singleton_is_real_singleton: is_real_singleton Enforces single instance property 11/20/2018 COSC6431

11 Instance Accessor Class
class INSTANCE_ACCESSOR inherit SINGLETON_ACCESSOR rename singleton as the_instance end feature the_instance: SINGLE_INSTANCE_CLASS is -- Create the only instance in the system once create Result.make(…) end 11/20/2018 COSC6431

12 Single Instance Class class INSTANCE inherit SINGLETON
creation {INSTANCE_ACCESSOR} make feature the_singleton: INSTANCE is once Result := Current end 11/20/2018 COSC6431

13 Most design patterns are…
More involved A larger number of classes and objects take part Language independent The pattern concept can be implemented in any OO language Let’s look at some examples… 11/20/2018 COSC6431

14 Observer Pattern Intent Also known as Define one-to-many dependency
When one subject changes state, all observers (dependents) are notified and correspondingly updated Also known as Dependents and Publish-Subscribe 11/20/2018 COSC6431

15 Observer – Motivation text view Notify change Request modification
A is 30% B is 50% C is 20% Notify change Request modification target view bar view rectangle view 11/20/2018 COSC6431

16 Observer Architecture
SUBJECT observers : set[…] update * attach(observer) detach(observer) notify TARGET_VIEW + subject update + TEXT_VIEW get_state set_state BAR_VIEW + subject update + subject RECTANGLE_VIEW + update + 11/20/2018 COSC6431

17 Observer – Participants
Subject Knows its observers Provides interface for attaching, detaching and notifying its observers Observer Defines an updating interface for observers 11/20/2018 COSC6431

18 Observer – Participants – 2
Concrete subject Stores state of interest to concrete observers Notifies observers when state changes Concrete observer Maintains a reference to its concrete subject Stores state that corresponds to the state of the subject Implements Observer updating interface 11/20/2018 COSC6431

19 Observer – Scenario Concrete subject updates all observers, when state is changed by a client CLIENT 2 1 1 set_state 2 notify 3 update 4 get_state Scenario: Update observers CONCRETE_SUBJECT 3 4 CONCRETE_OBSERVER 11/20/2018 COSC6431

20 Observer – Consequences – 1
Abstract coupling between subject and observer Permits changing number of observers dynamically Subject and observer can belong to different layers If they are in one class, then the object spans system layers, which can compromise abstraction by layering Supports broadcast communication Can have observers depend upon more than one subject 11/20/2018 COSC6431

21 Observer – Consequences – 2
Observers may also change the state Can be expensive as observers are unaware of each other Hard to assess the impact of a change Need additional protocol to indicate what changed Can have spurious updates Not all observers participate in all changes Can have clients notify, instead of subject, as clients understand better when updates are needed Leads to errors as clients can forget to update 11/20/2018 COSC6431

22 Observer – Consequences – 3
Dangling references when subject is deleted Notify observers when subject is deleted Not an issue in an environment with garbage collection 11/20/2018 COSC6431

23 Composite Pattern Intent
Compose objects into tree structures representing part-whole hierarchies Clients deal uniformly with individual objects and hierarchies of objects 11/20/2018 COSC6431

24 Composite – Motivation
Applications that have recursive groupings of primitives and groups Drawing programs lines, text, figures and groups Containment structure Subsystems and files Operations on groups are different than primitives but users treat them in the same way 11/20/2018 COSC6431

25 Composite – Drawing Example
DIAGRAM TEXT LINE DIAGRAM OVAL TEXT 11/20/2018 COSC6431

26 Composite Architecture
GRAPHIC * draw * T COMPOSITE[T] * add * remove * iterate * CLIENT DIAGRAM + draw + add + remove + iterate + LINE + TEXT + OVAL + draw + draw + draw + 11/20/2018 COSC6431

27 Composite – Applicability
Represent part-whole hierarchies of objects Clients can ignore difference between individual objects and compositions Clients deal with all objects in a composition in the same way 11/20/2018 COSC6431

28 Composite – Participants
Component Defines properties of an entity Leaf Defines properties of a primitive entity Composite Declares properties of a collection of entities Composite Component Combines properties of a collection of entities and properties of a primitive entity Client Uses component and composite properties 11/20/2018 COSC6431

29 Composite – Consequences
Whenever client expects a primitive it can accept a composite Client is simplified by removing tag-case statements to identify parts of the composition Easy to add new components by subclassing, client does not change If compositions are to have restricted sets of components have to rely on run-time checking 11/20/2018 COSC6431

30 Decorator Pattern Intent
Attach additional responsibilities to an object dynamically. Provide a flexible alternative to subclassing for extending functionality 11/20/2018 COSC6431

31 Decorator – Motivation
Motivation – Applicability Want to add responsibility to individual objects not to entire classes Add properties like border, scrolling, etc to any user interface component as needed Enclose object within a decorator object for flexibility Nest recursively for unlimited customization 11/20/2018 COSC6431

32 Decorator – Example Compose a border decorator with a scroll decorator for text view. a_border_decorator component a_scroll_decorator component a_text_view 11/20/2018 COSC6431

33 Decorator – Example Diagram
VISUAL_COMPONENT * draw * TEXT_VIEW + DECORATOR * draw component : VISUAL_ COMPONENT SCROLL_DECORATOR + BORDER_DECORATOR + draw scroll_position scroll_to draw border_width draw_border 11/20/2018 COSC6431

34 Decorator – Applicability
Add responsibilities to individual objects dynamically and transparently Without affecting other objects For responsibilities that can be withdrawn When subclass extension is impractical Sometimes a large number of independent extensions are possible Avoid combinatorial explosion Class definition may be hidden or otherwise unavailable for subclassing 11/20/2018 COSC6431

35 Decorator – General Structure
COMPONENT * method * CONCRETE_COMPONENT + DECORATOR * method component : COMPONENT CONCRETE_DECORATOR_ A + CONCRETE_DECORATOR_B + method other_feature method another_feature 11/20/2018 COSC6431

36 Decorator – Participants
Component defines the interface for objects that can have responsibilities added to them dynamically Concrete component Defines an object to which additional responsibilities can be attached Decorator Maintains a reference to a component object and defines an interface that conforms to COMPONENT Concrete decorator Add responsibilities to the component 11/20/2018 COSC6431

37 Decorator – Consequences
Benefits More flexibility than static inheritance Can add and remove responsibilities dynamically Can handle combinatorial explosion of possibilities Avoids feature laden classes high up in the hierarchy Pay as you go when adding responsibilities Can support unforeseen features Decorators are independent of the classes they decorate Functionality is composed in simple pieces 11/20/2018 COSC6431

38 Decorator – Consequences – 2
Liabilities From object identity point of view, a decorated component is not identical Decorator acts as a transparent enclosure Cannot rely on object identity when using decorators Lots of little objects Often result in systems composed of many look alike objects Differ in the way they are interconnected, not in class or value of variables Can be difficult to learn and debug 11/20/2018 COSC6431

39 Visitor Pattern Intent
Represent an operation to be performed on all of the components of an object structure Define new operations on a structure without changing the classes representing the components 11/20/2018 COSC6431

40 Visitor – Motivation Representing computer equipment EQUIPMENT *
Operations spread out OO style but ... difficult to add a new operation describe * price * FLOPPY_DISK + COMPOSITE_EQUIPMENT + .... describe + price + describe + price + 11/20/2018 COSC6431

41 Visitor Architecture Equipment classes are independent of the operations Equipment accept visitors and direct them to the appropriate operation – through polymorphism * EQUIPMENT_VISITOR accept * EQUIPMENT + PRICING_VISITOR + CHASSIS accept visit_chassis One subclass of EQUIPMENT_VISITOR for each operation One subclass of EQUIPMENT for each concrete piece of equipment 11/20/2018 COSC6431

42 Visitor – Applicability
Object structure contains many classes of objects with differing interfaces and want to perform operations that depend on their concrete classes Many distinct and unrelated operations need to be performed Do not want to or are unable to clutter the concrete classes with these operations Keep the related operations together, e.g. operations on pricing various types of EQUIPMENT are all in the PRICING_VISITOR class If the object structure is shared by many applications, Visitor puts operations into only those applications that need them 11/20/2018 COSC6431

43 Visitor – Applicability – 2
The classes defining the object structure rarely change, but you often want to define new operations over the structure Changing object structure means redefining interface to all visitors, which is costly If object structure changes often, Visitor is inappropriate 11/20/2018 COSC6431

44 Visitor – Abstract Architecture
ELEMENT * visit_elem_A ( ELEM_A ) * visit_elem_B ( ELEM_B ) * ... accept ( VISITOR ) * ... ELEM_A + CONCRETE_VISITOR_1 + accept ( VISITOR ) + ... visit_elem_A ( ELEM_A ) + visit_elem_B ( ELEM_B ) + ... ELEM_B CONCRETE_VISITOR_2 + 11/20/2018 COSC6431

45 Visitor – Participants
Element Declares accept method that takes a visitor as an argument Concrete element Implements the accept method Visitor Declares a visit operation for each concrete element class 11/20/2018 COSC6431

46 Visitor – Participants – 2
Concrete visitor Implements every visit operation declared in Visitor Each visit operation implements a fragment of the algorithm defined for the concrete visitor Provides the context for the algorithm composed of all of the visit fragments State accumulates with each visit Implements the high level organization Iteration over the components Processing each in turn 11/20/2018 COSC6431

47 Visitor – Scenario A pricing visitor visits a composite equipment
For each equipment, the pricing visitor selects which method from the EQUIPMENT_VISITOR interface to execute Scenario: Visit a cabinet 1 Accept the pricing visitor 2 visit_cabinet 3 visit_children 4 Accept the pricing visitor PRICING_VISITOR CABINET 1 2 MAIN 3 4 CHASSIS 11/20/2018 COSC6431

48 Visitor – Consequences
Adding new operations is easy New operation implements the Visitor interface, e.g. the methods in EQUIPMENT_VISITOR All the fragments of the visitor algorithm are in one file – related behaviours are together Easier to make sure that elements are working in unison Unrelated operations and fragments are in other visitor classes Contrast with having to change each of the concrete element classes to have the operation fragment Each class has a fragment of each of the operations 11/20/2018 COSC6431

49 Visitor – Consequences – 2
Adding new concrete elements is difficult Need to modify the Visitor interface Need to modify each concrete visitor Can sometimes simplify as many elements have common behaviour (default behaviour) that can be specified at concrete visitor level 1. Create subclasses of level 1 for more specific behaviour for the new elements Only program the new elements For many structures elements do not change rapidly so this is not a problem 11/20/2018 COSC6431

50 Visitor – Consequences – 3
One can visit object structures composed of unrelated objects The various visit_* methods do not have to take arguments that are related The main difference between Visitor and Iterator State accumulation Visitors contain data structures related to the operation they implement, e.g. the PRICING_VISITOR contains the total price Without a visitor, such data would have to be passed as arguments (or become global variables) 11/20/2018 COSC6431

51 Detecting design patterns
A difficult task Patterns are primarily a literary form No rigorous mathematical definitions Automatic detection beyond the state of the art of Artificial Intelligence Instead, detect the artifacts of implementing the solution of the design pattern 11/20/2018 COSC6431

52 Detecting design patterns
Purely structural patterns are easier to detect Purely behavioural patterns are much harder Most patterns are somewhere in the middle 11/20/2018 COSC6431

53 Template solution A template solution needs to be both:
Distinctive The static structure is not likely to be represented in a design that does not use the pattern Unambiguous Can only be done in one way (or in a small number of variants) An object adapter is unambiguous but not distinctive 11/20/2018 COSC6431

54 Adapter – Example EDITOR expects a SHAPE TEXT_VIEW is not a SHAPE
TEXT is a SHAPE Features are mapped (body calls relevant method) to TEXT_VIEW SHAPE EDITOR FIGURE TEXT TEXT_VIEW 11/20/2018 COSC6431

55 Analysis synergy Both static and dynamic analysis are necessary in order to detect patterns Static analysis The static structure of the pattern has to match a subgraph of the static structure of the software system Dynamic analysis Message passing during run-time has to match the message flow that implements the behaviour of the pattern 11/20/2018 COSC6431

56 An example Composite vs. Decorator
A Decorator is sometimes referred to as a degenerate Composite. The static structure of the two patterns is very similar The dynamic behaviour is also the same The difference is in the intent. The Composite pattern groups components into a whole. The Decorator patterns enhances the responsibility of a component. 11/20/2018 COSC6431

57 Kramer – Prechelt 96 Patterns detected: Structural (Adapter, Bridge, Composite, Decorator, Proxy) Each pattern expressed as a set of Prolog rules No dynamic information used Reported precision: 40% 11/20/2018 COSC6431

58 Antoniol et al. 98 Same patterns detected No handling of polymorphism
Metrics were employed to help reduce false positives Precision: 14 – 50% 11/20/2018 COSC6431

59 SPOOL A Bell Canada / University of Montreal project
Patterns detected: Template Method, Factory Method, Bridge Design information stored in an OODBMS Querying the database was able to recover many instances of patterns from three large C++ systems 11/20/2018 COSC6431

60 Niere et al. 01 Semi-automatic approach
Programs described in the form of Abstract Syntax Graphs Patterns described as graph transformations Limitation: Each variant has to be described as a separate transformation 11/20/2018 COSC6431

61 IDEA Detects patterns in UML diagrams
May suggest improvements on the application of the pattern (better naming, export status for features etc). Many patterns cannot be accurately detected from diagrams 11/20/2018 COSC6431

62 Heuzeroth et al. We covered this one already… 11/20/2018 COSC6431


Download ppt "Design Pattern Detection"

Similar presentations


Ads by Google