Design Patterns. Overview

Size: px
Start display at page:

Download "Design Patterns. Overview"

Transcription

1 Design Patterns Overview The need to manage complexity Place of data structures and algorithms Class diagrams in UML Beyond objects to patterns Example pattern Reference: Gamma et.al. chapter CS351 - Software Engineering (AY2004) 2 1

2 Managing software complexity There is a desperate need to be able to generate complex, reliable software. increasing functionality increasing machine capacity decreasing software quality Examples of poor software quality? CS351 - Software Engineering (AY2004) 3 How can you manage complexity? Software? Filing system? Building a house? structure? components? techniques? processes? Let s concentrate on structure and see how we can manage complexity there. CS351 - Software Engineering (AY2004) 4 2

3 We tend to learn programming bottom-up Start with simple values and variables integers, booleans, reals assignment, conditional statements, loops Work up to data structures sets of values in relationship commonly occurring abstractions arrays, linear lists, stacks, queues trees, graphs Examine interplay between data structures and algorithms choice of data structure affects efficiency of algorithm CS351 - Software Engineering (AY2004) 5 Data structures and classes In object-oriented terms, data structures and associated algorithms are usually described by abstract data types and encapsulated in objects or classes. e.g. List, Tree, Graph, Trie, etc. Get the data structures right and everything else will follow How do you get the data structures right? How do you get the classes right? How do you get a broader view of a system? Another level of abstraction? consider classes as components What are good ways of combining classes? combine classes to give design patterns CS351 - Software Engineering (AY2004) 6 3

4 Abstraction given by class diagrams Can represent classes as nodes in a graph, with edges giving the relationships between the classes Nodes can indicate state, behaviour (, identity) of classes State = attributes associated such an object (the instance variables). Behaviour = operations applicable to such an object (the instance methods). Identity = unique value that differentiates one object from another (usually implicit) Examples Bank account University professor CS351 - Software Engineering (AY2004) 7 Nodes can indicate more detail Note: included attributes do not include references to other objects include these by associations Types: e.g. balance: real e.g. deposit(amount: real): void Access control: public: + balance: real protected: # balance: real private: balance: real CS351 - Software Engineering (AY2004) 8 4

5 Nodes can indicate more detail Identify class variables and methods by underlining Annotate special kinds of components with stereotypes e.g. «constructor» BankAccount() e.g. «interface» Graph CS351 - Software Engineering (AY2004) 9 Class relationships Classes are related to other classes a GraphBase class may implement a Graph interface a GraphImp class may use NodeImp and EdgeImp classes a SavingsAccount class may extend a BankAccount class These relationships are drawn as arcs in the class diagram CS351 - Software Engineering (AY2004) 10 5

6 Edge annotations (Central) label indicates significance of association context determines which way to read the association e.g. an Edge joins two Nodes End-point labels indicate roles implications for implementation Multiplicity indicates number of participants e.g. optional: 0..1 e.g. zero or more: 0..* e.g. one or more: 1..* Node label setlabel(lbl) getlabel() 2 node joins 1 edge Edge label setlabel(lbl) getlabel() CS351 - Software Engineering (AY2004) 11 Edge annotations Arrow heads indicate navigation direction bidirectional navigation unidirectional navigation implications for implementation Style of arrow: e.g. inherits: A inherits B e.g. implements: A implements B e.g. aggregates: A aggregates B e.g. composite: A is a composite of B CS351 - Software Engineering (AY2004) 12 6

7 Aggregates vs composites Aggregates and composites indicate a special association their use is optional Aggregates indicate a part-whole relationship Composites indicate a part-whole relationship where the whole strongly owns the parts Copy/delete the whole? copy/delete the parts E.g. student enrolled in a degree no aggregation E.g. degree includes compulsory course aggregation not composite courses may belong to multiple degree E.g. building consists of 4 floors composite floors cannot belong to more than one building CS351 - Software Engineering (AY2004) 13 Specializing BankAccount Inheritance and software reuse A bank account with an overdraft facility A tenured vs contract University teacher Reuse state and behaviour Fundamental to the provision of Graphical User Interfaces. CS351 - Software Engineering (AY2004) 14 7

8 Relating BankAccount and Custome Objects can use other objects to accomplish their tasks A bank account could have an associated customer The customer object could be notified about overdrafts Reuse state and behaviour Maintains encapsulation CS351 - Software Engineering (AY2004) 15 Inheritance vs Composition Inheritance has been promoted as the reuse mechanism Experience shows that composition is a cleaner mechanism Inheritance hierarchies can become overly complex Inheritance breaks encapsulation (at least partially) Inheritance is a static compile-time mechanism, while composition can be a dynamic run-time mechanism (added flexibility may be good or bad) Implementation of parent will affect that of the child CS351 - Software Engineering (AY2004) 16 8

9 Unified Modeling Language (UML) Previous class diagram notation is part of the Unified Modelling Language (UML) arose out of other notations: OMT, Booch, Jacobsen UML also addresses other models Use Case diagrams for capturing external interactions State diagrams for capturing the internal class activity Interaction diagrams for capturing interaction between classes Sequence diagrams for capturing more detailed interaction between classes Deployment diagrams for relating software to available hardware... CS351 - Software Engineering (AY2004) 17 Beyond objects Object-oriented software construction is not enough Typical systems have a large number of objects/classes Relationships between classes can be very complex Becomes unmanageable Consider commonly occurring sets of classes patterns E.g. contract for house sale speaks in terms of Vendors, Purchasers, Premises, Chattels, etc. A set of objects is required for such a contract CS351 - Software Engineering (AY2004) 18 9

10 Beyond patterns Patterns may not be enough to structure complex software You may require a higher level view of the system This leads to the topic of software architecture... CS351 - Software Engineering (AY2004) 19 Example: the Adapter (class) pattern Consider wanting to use a prebuilt component which does not match the interface you assumed very common when you try to reuse software CS351 - Software Engineering (AY2004) 20 10

11 Example: the Adapter (class) example Consider supplying a bank account (as above) in terms of an account which has a single method for changes CS351 - Software Engineering (AY2004) 21 Example: the Adapter (object) pattern Consider wanting to use a prebuilt component which does not match the interface you assumed Adaptee is used, not inherited CS351 - Software Engineering (AY2004) 22 11

12 Example: the Adapter (object) pattern Consider needing a bank account (as above) in terms of an account which has a single method for changes. CS351 - Software Engineering (AY2004) 23 Where next? Describing and classifying patterns Creational patterns for more flexible object creation Reference: Gamma et.al. chapters CS351 - Software Engineering (AY2004) 24 12

13 Reminder Patterns capture solutions to commonly occurring problems Many problems arise in the context of GUIs Authors need to identify 3 distinct uses/contexts before classifying the solution as a pattern Patterns consist of a number of classes which interact in a certain way (to solve the problem) Patterns may or may not be applicable in a given context Many patterns introduce extra levels of indirection Most problems in Computer Science can be solved with an extra level of indirection CS351 - Software Engineering (AY2004) 25 Description of patterns Name succinct indication of pattern s purpose Synopsis short description of the pattern (for experienced users) Context problem description + example problem Forces considerations leading to the solution Solution describes the general-purpose solution Consequences trade-offs and results Implementation pitfalls, hints, techniques Sample code Related patterns similar sorts of situations CS351 - Software Engineering (AY2004) 26 13

14 Example description Adapter pattern Name: Adapter Class, Object Structural Synopsis: implements an interface known to the clients via a class which is not known to the clients Context: the class interfaces derived from the design of a system may not match the class interface available in a reusable library. E.g. BankAccount class with two methods deposit(amount) and withdraw(amount) to be adapted to a class Account which has a single method change(amount) which accepts positive and negative amounts. Forces: You want to use an existing class, and its interface does not match the one you need You do not have the option of changing the interface of the existing class maybe the source isn t available, or the class is part of a reusable library CS351 - Software Engineering (AY2004) 27 Example description Adapter pattern Solution: A class adapter uses multiple inheritance to adapt one interface to another. An object adapter relies on object composition: Target defines the domain-specific interface that Client uses Client collaborates with objects conforming to the Target interface Adaptee defines an existing interface that needs adapting Adapter adapts the interface of Adaptee to the Target interface CS351 - Software Engineering (AY2004) 28 14

15 Example: the Adapter (class) pattern Reuse a prebuilt class which does not match the interface you assumed very common when you try to reuse software CS351 - Software Engineering (AY2004) 29 Java-line code for Adapter class pattern abstract class Target // Maybe an interface { public abstract ResultType request(); } class Adaptee // An existing class { public ResultType req() { } } CS351 - Software Engineering (AY2004) 30 15

16 Java-line code for Adapter class pattern class Adaptor extends Target, Adaptee { public ResultType request() { return req(); // Use Adaptee version } } Note that Java does not support multiple inheritance the above would be possible in C++, Eiffel the above would be possible if Target were an interface, in which case Adaptor would inherit Adaptee and implement Target CS351 - Software Engineering (AY2004) 31 The Adapter (object) pattern Consider wanting to use a prebuilt component which does not match the interface you assumed CS351 - Software Engineering (AY2004) 32 16

17 Java-like code for Adapter object pattern Target and Adaptee classes as before class Adaptor extends Target // Does not inherit Adaptee { Adaptee adpt = new Adaptee(); public ResultType request() { return adpt.req(); // Use Adaptee version } } Note that this works directly in Java CS351 - Software Engineering (AY2004) 33 Example description: Adapter pattern Consequences: Class and object adapters have different tradeoffs. A class adapter adapts Adaptee to Target by committing to a concrete Adapter class. As a consequence, a class adapter won t work when we want to adapt a class and all its subclasses. lets Adapter override some of Adaptee s behaviour, since Adapter is a subclass of Adaptee introduces only one object, and no additional pointer indirection is needed to get to the Adaptee. CS351 - Software Engineering (AY2004) 34 17

18 Example description: Adapter pattern Consequences: Class and object adapters have different tradeoffs. An object adapter lets a single Adapter work with many Adaptees, i.e. the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. makes it harder to override Adaptee behaviour. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself. Related patterns: Facade, Proxy, Strategy CS351 - Software Engineering (AY2004) 35 Classification of patterns There are two basic dimensions of classification Scope: application primarily to classes or objects? Purpose: creational for creating (and deleting) objects structural for composing classes or objects behavioural interaction of classes or objects CS351 - Software Engineering (AY2004) 36 18

19 Example classification: Adapter pattern Adapter is of scope class or object Adapter is of purpose structural CS351 - Software Engineering (AY2004) 37 Creational patterns These patterns provide alternatives to creation of objects by using the new function which: fixes the class of object being created i.e. lacks flexibility / configurability is independent of other calls to new i.e. does not relate creation of different kinds of objects Suppose we have a situation where a number of related objects (or products) need to be created e.g. set of graphical components with similar look-and-feel e.g. set of bank accounts with matching audit provisions A common problem! CS351 - Software Engineering (AY2004) 38 19

20 Abstract factory object creational Synopsis: Provides a way to create instances of abstract classes from a matched set of concrete subclasses Context: Consider building a GUI framework which should work with multiple windowing systems (e.g. Windows, Motif, MacOS) and should provide consistent look-and-feel. Forces: Use the Abstract Factory pattern when: a system should be independent of how its products are created, composed and represented a system should be configured with one of multiple families of products a family of related products is designed to be used together, and you need to enforce this constraint you want to provide a class library of products, and only reveal their interfaces, not their implementations CS351 - Software Engineering (AY2004) 39 Abstract factory object creational Solution: Define an abstract factory class which has methods to generate the different kinds of products. (For a windowing system this could generate matched buttons, scroll bars, fields). The abstract factory is subclassed for a particular concrete set of products AbstractFactory declares an interface for operations that create abstract product objects ConcreteFactory implements the operations to create concrete product objects AbstractProduct declares an interface for a type of product object ConcreteProduct implement the AbstractProduct interface Client uses only the interfaces declared by AbstractFactory and AbstractProduct classes CS351 - Software Engineering (AY2004) 40 20

21 Abstract factory object creational CS351 - Software Engineering (AY2004) 41 Abstract factory object creational Consequences: It isolates concrete classes clients are isolated from implementation classes clients manipulate instances through their abstract interfaces It makes exchanging product families easy It promotes consistency among products Supporting new kinds of product is difficult the AbstractFactory interface fixes the set of products that can be created extending the AbstractFactory interface will involve changing all of the subclasses The hierarchy of products is independent of the client CS351 - Software Engineering (AY2004) 42 21

22 Lexi: consistent look-and-feel CS351 - Software Engineering (AY2004) 43 Java code for Abstract Factory pattern abstract class Product1 // Some kind of object { } abstract class Product2 // Another kind of object { // - related to Product1 } abstract class AbstractFactory { public abstract Product1 createproduct1(); public abstract Product2 createproduct2(); } CS351 - Software Engineering (AY2004) 44 22

23 Java code for Abstract Factory pattern class version1product1 extends Product1 // Specific kind { // of Product1 } class version1product2 extends Product2 // Specific kind { // of Product2 } class version2product1 extends Product1 // Another kind { // of Product1 } class version2product2 extends Product2 // Another kind { // of Product2 } CS351 - Software Engineering (AY2004) 45 Java code for Abstract Factory pattern class version1factory extends AbstractFactory { // Factory for version1 products public Product1 createproduct1() { return new version1product1(); } public Product2 createproduct2() { return new version1product1(); } } Similarly for a class version2factory CS351 - Software Engineering (AY2004) 46 23

24 Java code for Abstract Factory pattern class client { static void main() { AbstractFactory fact = new version1factory();... fact.createproduct1() // version1 products... fact.createproduct2() } } With the one line fact = new version2factory(), you would end up with version2 products CS351 - Software Engineering (AY2004) 47 Creational patterns In the abstract factory the family of related products was independent of the client(s) A GUI framework needs to generate related products, but the products depend on the structure of the client classes e.g. a word-processor application needs to generate wordprocessor documents, and word-processor documents need to be displayed in word-processor views Solution is to define methods in the (generic) client classes to create (generic) objects then override these methods in a specific application CS351 - Software Engineering (AY2004) 48 24

25 Sample: generic application and documents CS351 - Software Engineering (AY2004) 49 Factory method class creational Synopsis: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses Context: Example is that of a GUI framework. The generic Application class will have a method createdocument to create a generic document. A specific use of the framework for, say, word-processing GUI would subclass the generic Application class and override the createdocument method to generate word-processing documents. Forces: Use the Factory Method pattern when: a class can t anticipate the class of objects it must create a class wants its subclasses to specify the objects it creates the set of classes to be generated may be dynamic CS351 - Software Engineering (AY2004) 50 25

26 Factory method class creational Solution: Use a factory method to create the instances: Product (e.g. Document) defines the interface of objects the factory method creates ConcreteProduct (e.g. MyDocument) implements the Product interface Creator (e.g. Application) declares the factory method which returns an object of type Product (possibly with a default implementation); may call the factory method to create a Produce object ConcreteCreator (e.g. MyApplication) overrides the factory method to return an instance of ConcreteProduct CS351 - Software Engineering (AY2004) 51 Factory method class creational CS351 - Software Engineering (AY2004) 52 26

27 Factory method class creational Consequences: It eliminates the need to bind application-specific classes into your code. The code only deals with the Product interface and therefore can work with any user-defined ConcreteProduct classes. A client will have to subclass the Creator class just to create a particular ConcreteProduct instance. Provides hooks for subclasses to provide extended versions of objects Connects parallel class hierarchies, e.g. Application Document vs MyApplication MyDocument The set of product classes that can be instantiated may change dynamically CS351 - Software Engineering (AY2004) 53 Structural patterns Reference: Gamma et al.: Chapter 4. These patterns allow you to achieve different relationships between classes or objects Adapter is a structural pattern Consider a situation where you have some recursive composition of objects e.g. consider a document formatting program that formats characters into lines, lines into columns, columns into pages suppose that columns can contain frames which can contain columns the recursive structure can get rather complicated CS351 - Software Engineering (AY2004) 54 27

28 Structural patterns CS351 - Software Engineering (AY2004) 55 Composite object structural Synopsis: Allows you to build complex objects by recursively composing similar objects in a treelike manner, representing whole-part hierarchies Context: In a document-formatting program (such as described previously), the complex inclusion relationships can lead to complex code. This is made worse if you try to handle primitive and container objects differently. The key to the pattern is to define an abstract class which represents both primitive and composite components Forces: you have a complex object that needs to be decomposed into a part-whole hierarchy you want to minimise the complexity of the part-whole hierarchy by minimising the number of different kinds of child objects CS351 - Software Engineering (AY2004) 56 28

29 Composite- object structural Solution: Provide an abstract superclass for all objects in the hierarchy and an abstract superclass for all composites in the hierarchy AbstractComponent the common superclass for all objects in the hierarchy AbstractComposite the common superclass for all composite objects in the hierarchy. It inherits from AbstractComponent and has additional methods to add and remove components ConcreteComponent specific component in the hierarchy ConcreteComposite specific composite in the hierarchy CS351 - Software Engineering (AY2004) 57 Composite object structural CS351 - Software Engineering (AY2004) 58 29

30 Composite object structural Consequences: The tree-like composite object can be treated as consisting of AbstractComponents (whether they are simple or composite) Clients of AbstractComponent can ignore whether it is actually a composite or not An operation performed on an AbstractComposite treated as an AbstractComponent can be delegated to the component objects Any AbstractComponent object can be a child of an AbstractComposite. More restrictive policies can be enforced. Related patterns: Chain of responsibility CS351 - Software Engineering (AY2004) 59 Composite object structural CS351 - Software Engineering (AY2004) 60 30

31 Glyph interface for Lexi All graphics, whether simple or composite, will have a common interface of a Glyph: interface Glyph { void Draw(Window) // to display itself Rect Bounds() // return the bounding rectangle Boolean Intersects(Point) // determine if the point is in the // bounding rectangle (and the glyph // needs to respond to some event) void Insert(Glyph, int) // add a component glyph void Remove(Glyph) // remove a glyph Glyph Child(int) // return a component glyph Glyph Parent() // return the parent glyph } CS351 - Software Engineering (AY2004) 61 Structural patterns Consider a situation where you want to control access to an object e.g. a distributed system where the application needs to interact with an object but it should not need to know whether the object is local or remote e.g. a word processor where you do not wish to open and display a (large) image unless it is required CS351 - Software Engineering (AY2004) 62 31

32 Example- text document with large images CS351 - Software Engineering (AY2004) 63 Proxy object structural Synopsis: Provide a surrogate or placeholder for another object to control access to it Context: A proxy object receives method calls from clients on behalf of another object. The proxy object does not provide the services directly but calls the methods of the object. Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer, such as: a remote proxy provides a local representative for an object in a different address space a virtual proxy creates expensive objects on demand a protection proxy controls access to the original object a smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed CS351 - Software Engineering (AY2004) 64 32

33 Proxy object structural Forces: the service-providing object cannot provide the service at a convenient time and place gaining visibility to an object is non-trivial and you want to hide the complexity you want to control access to the service-providing object CS351 - Software Engineering (AY2004) 65 Proxy object structural Solution: Proxy forwards requests to RealSubject when appropriate, depending on the kind of proxy Subject (e.g. Graphic) defines the common interface for RealSubject and Proxy so that Proxy can be used anywhere that RealSubject is expected RealSubject (e.g. Image) defines the real object that the proxy represents Proxy (e.g. ImageProxy) maintains a reference that lets the proxy access the real subject; provides an interface identical to Subject s so that a proxy can be substituted for the real subject; controls access to the real subject CS351 - Software Engineering (AY2004) 66 33

34 Proxy object structural CS351 - Software Engineering (AY2004) 67 Proxt object structural Consequences: The additional level of indirection in accessing an object can have many uses: a remote proxy can hide the fact that an object resides in a different address space a virtual proxy can perform optimisations such as creating an object on demand protection proxies and smart references allow additional housekeeping tasks when an object is accessed A Proxy can also be used to defer duplication of a (large) object until the duplicate is actually changed (and the copy needs to be generated) Related patterns: Facade, Decorator CS351 - Software Engineering (AY2004) 68 34

35 Structural patterns Consider a situation where you want to vary the implementation of an abstraction at run time e.g. given a fixed GraphBase you may want to vary the GraphImp at run-time (to suit particular algorithms) Consider a situation where you want to allow a number of related abstractions each with a number of different implementations it is then desirable for the abstractions and implementations to vary independently CS351 - Software Engineering (AY2004) 69 Example variety of windows and systems CS351 - Software Engineering (AY2004) 70 35

36 Bridge object structural Synopsis: Decouple an abstraction from its implementation so that they can vary independently Context: You can have hierarchies of windowing abstractions and hierarchies of windowing systems. If you combine the two, you will end up with too many classes. Forces: you want to avoid a permanent binding between an abstraction and its implementation both the abstractions and the implementations should be extensible by subclassing changes in the implementation of an abstraction should have no impact on clients you have a proliferation of classes (as in the example) you want to share an implementation among multiple objects CS351 - Software Engineering (AY2004) 71 Bridge object structural Solution: Abstractions have reference to the implementation and forward client requests as required Abstraction (e.g. Window) defines the abstraction s interface; maintains a reference to an object of type Implementor RefinedAbstraction (e.g. IconWindow) extends the interface defined by Abstraction Implementor (e.g. WindowImp) defines the interface for the implementation classes. This interface doesn t need to correspond exactly to the Abstraction s interface (but it may) ConcreteImplementor (e.g. XWindowImp) implements the Implementor s interface CS351 - Software Engineering (AY2004) 72 36

37 Bridge object structural CS351 - Software Engineering (AY2004) 73 Example variety of windows and systems CS351 - Software Engineering (AY2004) 74 37

38 Bridge object structural Consequences: Decoupling abstraction and implementation: an implementation is not bound permanently to a abstraction eliminates compile-time dependencies on the implementation, i.e. can change implementation class without necessarily recompiling Improved extensibility: the Abstraction and Implementation hierarchies can be extended independently Hiding implementation details from clients: e.g. clients don t need to know if implementations are shared Related patterns: Adapter, Factory method CS351 - Software Engineering (AY2004) 75 Where next? Structural patterns for more flexible object relationships Decorator Behavioral patterns for more flexible object interaction Strategy Iterator Reference:, Gamma et.al. chapter CS351 - Software Engineering (AY2004) 76 38

39 Structural patterns Sometimes you want to add capabilities/responsibilities to an individual object and not to a whole class e.g. you may want to display some objects in a GUI with embellishments like a border or drop shadow e.g. you may want to add scroll bars to a component only when it cannot be fully displayed in the window Using inheritance to add the capability means that all objects will have the additional properties (e.g. border) Another approach is to define a class to act as a filter: it encloses the object to be embellished it adds the capability required such a filter can be added as required CS351 - Software Engineering (AY2004) 77 Decorator object structural Synopsis: Add functionality (dynamically) to an object in a way which is transparent to its clients Context: In a GUI, you may want to add and retract embellishments of displayed objects, such as a border or shading or some highlight. It is not appropriate to add this to every displayed object, and further, you may wish to retract the embellishment without discarding the original object. Forces: You want to extend the functionality of a number of objects of a given class, but you do not want to add this to every instance There is a need to dynamically extend or withdraw the capabilities of objects CS351 - Software Engineering (AY2004) 78 39

40 Decorator object structural Solution: Define a class to act as a wrapper/filter for the original object and which adds the necessary functionality. Such a wrapper instance can be added or removed at runtime. Component defines the interface for objects which can have capabilities added dynamically ConcreteComponent defines the objects to which additional capabilities can be attached Decorator includes the Component interface, holds a reference to a component ConcreteDecorator adds the required capabilities to a Decorator CS351 - Software Engineering (AY2004) 79 Decorator object structural CS351 - Software Engineering (AY2004) 80 40

41 Decorator object structural Consequences: Decorator allows for dynamic change in the capabilities of components, by adding and removing wrappers You can mix and match with a number of wrappers achieving a large number of possible combinations Flexibility of wrappers makes them more error prone, e.g. using incompatible wrappers or getting circular references Use of decorators reduces the number of classes, but increases the number of objects (which can hinder debugging) The use of decorators makes it difficult to distinguish objects by their object identities Related patterns: Delegation, Filter, Strategy CS351 - Software Engineering (AY2004) 81 Behavioral patterns Consider a system that needs to break a stream of text into lines. There are many algorithms for doing this hardwiring a particular algorithm may be undesirable: clients will be more complex if they include the algorithm different algorithms will be appropriate at different times or in different contexts it is difficult to add new algorithms The solution is to define classes which encapsulate different line-breaking algorithms the so-called Strategy pattern CS351 - Software Engineering (AY2004) 82 41

42 Strategy object behavoral Synopsis: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it Context: In a document editor you may want to vary the choice of line-breaking strategies, possibly on-the-fly Forces: Use the Strategy pattern when: many related classes differ only in their behavior, in which case the Strategy provides a way of configuring a class with one of many behaviors you need different variants of an algorithm an algorithm uses data that clients shouldn t know about Strategy avoids exposing complex, algorithm-specific data structures a class defines multiple alternative behaviors CS351 - Software Engineering (AY2004) 83 Strategy object behavoral Solution: Encapsulate the algorithm in an object: Strategy (e.g. Compositor) declares an interface common to all supported algorithms. Context uses this interface to call the algorithms defined by a ConcreteStrategy ConcreteStrategy (e.g. SimpleCompositor) implements the algorithm using the Strategy interface Context (e.g. Composition) is configured with a ConcreteStrategy object, and may define an interface that lets Strategy access its data. CS351 - Software Engineering (AY2004) 84 42

43 Structural of strategy pattern CS351 - Software Engineering (AY2004) 85 Example: breaking test into lines Composition maintains line breaks in displayed text it uses a Compositor to determine those line breaks Compositor determines line breaks SimpleCompositor for plain text, TexCompositor for Tex algorithm, etc. CS351 - Software Engineering (AY2004) 86 43

44 Strategy object behavoral Consequences: The Strategy pattern has the following benefits and drawbacks: families of related algorithms can be defined using a class hierarchy, thus allowing common functionality of the algorithms to be factored out an alternative to subclassing for providing a variety of algorithms or behaviours. Subclassing for modifying behaviour hard-wires the behaviour into Context. Further, subclassing does not support dynamic modification of the algorithm Strategies can eliminate conditional statements used to select the particular algorithm Strategies provide a choice of implementations, depending for example, on different time and space tradeoffs CS351 - Software Engineering (AY2004) 87 Strategy object behavoral Consequences: The Strategy pattern has the following benefits and drawbacks: families of related algorithms can be defined using a class hierarchy, thus allowing common functionality of the algorithms to be factored out an alternative to subclassing for providing a variety of algorithms or behaviours. Subclassing for modifying behaviour hard-wires the behaviour into Context. Further, subclassing does not support dynamic modification of the algorithm Strategies can eliminate conditional statements used to select the particular algorithm Strategies provide a choice of implementations, depending for example, on different time and space tradeoffs CS351 - Software Engineering (AY2004) 88 44

45 Behavioral patterns Suppose we have an aggregate data structure and we wish to access the components without revealing the structure of the aggregate e.g. it would be nice to be able to write something like: for (Iterator i = s.iterator() i.hasnext();) { x=i.next();... e.g. we may have a Set data structure and wish to examine the elements of the set without revealing whether they are stored as an array, linked list, etc. Solution is to define an Iterator CS351 - Software Engineering (AY2004) 89 Iterator object behavoral Synopsis: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation Context: useful for accessing the components of any data structure, e.g. set, list, tree Forces: Use the Iterator pattern: to access an aggregate object s contents without exposing its internal representation to support multiple traversals of aggregate objects to provide a uniform interface for traversing different aggregate structures (i.e. to support polymorphic iteration) CS351 - Software Engineering (AY2004) 90 45

46 Iterator object behavoral Solution: Iterator defines an interface for accessing and traversing elements ConcreteIterator (e.g. PTListIterator) implements the Iterator interface; keeps track of the current position in the traversal of the aggregate Aggregate defines an interface for creating an Iterator object ConcreteAggregate (e.g. PTList) implements the Iterator creation interface to return an instance of the proper ConcreteIterator CS351 - Software Engineering (AY2004) 91 Example: a list iterator PTListIterator will need to have a reference to the list (as indicated by the arrow in the diagram) For scoping reasons (in Java), the PTListIterator will be declared as a public inner class of PTList only then will the hidden components of PTList be accessible to the iterator, cf. friend in C++ CS351 - Software Engineering (AY2004) 92 46

47 Iterator object behavoral Consequences: There are 3 important consequences: It supports variations in the traversal of an aggregate. Complex data structures may be traversed in many ways. Different iterators can be defined for different kinds of traversal Iterators simplify the Aggregate interface. The Aggregate does not need to supply extra functions for iteration, since they are now available in a separate class. More than one traversal can be pending on an aggregate. This is because each iterator keeps track of its own traversal state. The same effect would be more difficult if the aggregate stored the traversal state. You should query the robustness of the iterator what happens if the aggregate is changed during traversal? CS351 - Software Engineering (AY2004) 93 Java code for an iterator Code added to the PTSet class import java.util.iterator; import java.util.set; class PTSet implements Set { // class definition public class ElementIterator implements Iterator { // use the Iterator interface int currelt = 0; public boolean hasnext() { // part of the Iterator interface return currelt < numelements(); } public Object next() { // part of the Iterator interface Object result = null; // result will require coercion if (hasnext()) { result = item(currelt); currelt = currelt+1; } } return result; Use iterator Interface of Java } } public Iterator iterator() { // function to create an iterator return new ElementIterator(); } Generate iterator CS351 - Software Engineering (AY2004) 94 47

48 Java code for an interator Code added to the client class import java.util.iterator; class Client { // class definition for some client PTSet s = new PTSet(); // will process elements of set s for (Iterator iter = s.makeelementiterator(); iter.hasnext(); ) { // generate the iterator Element e=(element)iter.next(); } } CS351 - Software Engineering (AY2004) 95 Behavoral patterns In a GUI, it is common to support undoable operations you choose a graphical component and perform some operation on it After that you wish to be able to undo/redo it Alternatively, you may wish to have the facility for queuing operations, or scheduling them for later execution. The common way to support this functionality is with the Command pattern CS351 - Software Engineering (AY2004) 96 48

49 Command object behavoral Synopsis: Encapsulates a request as an object, thereby letting you parameterise clients with different requests, queue or log requests, and support undoable operations Context: support for undoable commands such as Cut, Copy and Paste in a GUI. Forces: Use the Command pattern when you want to: parameterise objects by an action to perform. (Commands are an object-oriented replacement for callbacks in procedural languages.) specify, queue, and execute requests at different times. The Command object can have a lifetime independent of the original request support undo, since a Command can store relevant state for reversing the effects of the command CS351 - Software Engineering (AY2004) 97 Command object behavoral Forces (ctd): Use the Command pattern when you want to: support logging changes so that they can be reapplied in case of a system crash structure a system around high-level operations built on primitive operations. Such a structures is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. CS351 - Software Engineering (AY2004) 98 49

50 Command object behavoral Solution: The requested operation is encapsulated in an object with sufficient data to be able to perform and undo it: Command declares an interface for executing an operation ConcreteCommand (e.g. PasteCommand) defines a binding between a Receiver object and an action; implements commit() by invoking the corresponding operation(s) on Receiver Client (e.g. Application) creates a ConcreteCommand object and sets its Receiver Invoker (e.g. MenuItem) asks the command to carry out the request Receiver (e.g. Document) knows how to perform the operations associated with carrying out a request CS351 - Software Engineering (AY2004) 99 Structure of command pattern CS351 - Software Engineering (AY2004)

51 Example: GUI commands CS351 - Software Engineering (AY2004) 101 Command object behavoral Consequences: Command decouples the object that invokes the operation from the one that knows how to perform it Commands are first-class objects they can be manipulated and extended like any other object You can assemble commands into a composite command You can add new commands without changing existing classes Related patterns: Strategy CS351 - Software Engineering (AY2004)

52 Motivating example for design patterns Graphical user interfaces (GUIs) are quite pervasive they are complex pieces of software their development relies heavily on object-orientation Much of the initial motivation for design patterns arose in the context of GUI development no coincidence that Gamma developed key GUI frameworks there are common problems in the GUI context there are standard solutions design patterns A GUI case study provides the context for demonstrating a number of design patterns CS351 - Software Engineering (AY2004) 103 Essential features of a GUI Graphical display windows icons menus User interaction via pointing device (mouse) + keyboard select window, navigate within a window select object as target for operation select operation via menus (or keyboard) Event-driven paradigm activity is determined by user interaction, not predetermined by program CS351 - Software Engineering (AY2004)

53 Event-driven paradigm Typically GUI style program read a graph if the user selects appropriate menu item modify display of graph in response to mouse activity perform analysis in response to menu item produce results if requested Structure of program is based around a central event loop repeatedly wait for an event and then process it CS351 - Software Engineering (AY2004) 105 Requirements for a document editor A significant design problem What are the issues to be addressed? Can we formulate the big picture? How effective are patterns for capturing the design choices? Document editor (called Lexi) in the style of Word, etc. Documents consist of text + graphics Manipulate individual or groups of components See fig 2.1 (Gamma et al) for sample screen image Want flexibility in many areas structure, algorithms, interface CS351 - Software Engineering (AY2004)

54 Design issues Document structure lexible composition of document components Formatting flexible, configurable formatting policies Embellishing the user interface scroll bars, borders, drop shadows, etc. Multiple look-and-feel standards can t be hard-wired into the application Multiple windowing systems for portability User operations which are undoable Spell checking and hyphenation won t be considered CS351 - Software Engineering (AY2004) 107 Document structure A document consists of graphical components such as characters, lines, polygons, other shapes The author will view the document as groups of components rows, columns, figures, tables, etc. Lexi should allow the author to manipulate these groups directly The internal document structure should support: maintaining the document s physical structure generating and presenting the document visually mapping positions on the display to document components (in response to mouse activity) CS351 - Software Engineering (AY2004)

55 Document structure Proposal is to have a recursive structure for graphical components CS351 - Software Engineering (AY2004) 109 Document structure Internal structure corresponding to previous slide will be treestructured: CS351 - Software Engineering (AY2004)

56 Formatting strategies Variety of issues could be addressed e.g. how to break up the components into lines what are the formatting policies? can they be configured on demand? Want to support a variety of strategies independent of the document structure CS351 - Software Engineering (AY2004) 111 Embellishing the user interface Want to support scroll bars, borders, etc. Want to be able to do this uniformly and flexibly vary these as the user interface evolves even add and remove them on the fly therefore can t have a fixed inheritance structure Set up a structure for transparent enclosures (like a filter) each enclosure has one component drawing interface is the same as for the component clients don t know if they are dealing with the component or the enclosure CS351 - Software Engineering (AY2004)

57 Multiple look-and-feel standards Look-and-feel is determined by a family of GUI components buttons, scroll bars, pop-up menus, etc. called widgets Need to be able to generate consistent sets of widgets suit a variety of styles, e.g. Motif, Windows, MacOS, CS351 - Software Engineering (AY2004) 113 Multiple windowing systems Want to support multiple window systems for portability these vary in the level of functionality should we define an abstract windowing system and then inherit it and override it to satisfy specific cases? support the minimum functionality? maximum? Simpler to define a windowing system that suits our needs allow this to have a variety of implementations each implementation decides how to implement the required operations CS351 - Software Engineering (AY2004)

58 Undoable operations User can request operations from different contexts menu selection mouse operation palette Request need to encapsulate relevant state information so that they can be undone CS351 - Software Engineering (AY2004) 115 GUI frameworks Even with object orientation, developing a GUI is hard work learning curves of 18 months used to be quoted Java APIs make it a lot easier Significant breakthrough came with GUI frameworks A framework is a set of cooperating classes that make up a reusable design for a specific class of software It is a skeleton application which can be refined by inheritance There are frameworks for GUIs, compiler construction, financial modelling CS351 - Software Engineering (AY2004)

59 GUI frameworks A GUI framework will include: generic application which will include the central event loop central event loop will distribute events to relevant graphical components generic documents = file with contents displayed in a window generic windows with title bar, close box, resize control, scroll bar generic dialog windows with the ability to display check boxes, radio controls, buttons, etc. configurable menu manipulation CS351 - Software Engineering (AY2004) 117 Generic application The Generic Application is typically encoded in a class called Application this class is subclassed for a specific application The Application class typically: includes the central event loop which is never modifiable is instantiated once for a given run of the application may handle multiple document types has method(s) to generate documents has method(s) to setup and respond to appropriate menus CS351 - Software Engineering (AY2004)

60 Generic document The Generic Document is typically encoded in a class called Document this class is subclassed for different specific documents The Document class typically: is instantiated once per document to be processed has methods for fetching and storing the document as a file has method(s) to display the document contents has method(s) to setup and respond to appropriate menus CS351 - Software Engineering (AY2004) 119 Generic view The Generic View is typically encoded in a class called View this class is subclassed for different specific graphical components The View class typically: corresponds to an arbitrarily large drawing surface contains functionality to render and print the component contains functionality to maintain the current selection supports various possible representations of the same data, e.g. spreadsheet, graph, etc. has method(s) to respond to mouse events CS351 - Software Engineering (AY2004)

61 Generic window The Generic Window is typically encoded in a class called Window this class is subclassed for different operating systems The Window class typically: implements window-related methods like moving, resizing, closing contains methods to optimise screen updating may contain components to clip the display Note that a View is a logical entity which is displayed in the physical entity of a Window CS351 - Software Engineering (AY2004) 121 Generic classes and relationships Application has multiple documents Document has multiple views View is displayed in a physical region Window contains multiple regions CS351 - Software Engineering (AY2004)

62 CS351 - Software Engineering (AY2004)

Design of Software Systems (Ontwerp van SoftwareSystemen) Design Patterns Reference. Roel Wuyts

Design of Software Systems (Ontwerp van SoftwareSystemen) Design Patterns Reference. Roel Wuyts Design of Software Systems (Ontwerp van SoftwareSystemen) Design Patterns Reference 2015-2016 Visitor See lecture on design patterns Design of Software Systems 2 Composite See lecture on design patterns

More information

Design Patterns IV Structural Design Patterns, 1

Design Patterns IV Structural Design Patterns, 1 Structural Design Patterns, 1 COMP2110/2510 Software Design Software Design for SE September 17, 2008 Class Object Department of Computer Science The Australian National University 18.1 1 2 Class Object

More information

Design Patterns IV. Alexei Khorev. 1 Structural Patterns. Structural Patterns. 2 Adapter Design Patterns IV. Alexei Khorev. Structural Patterns

Design Patterns IV. Alexei Khorev. 1 Structural Patterns. Structural Patterns. 2 Adapter Design Patterns IV. Alexei Khorev. Structural Patterns Structural Design Patterns, 1 1 COMP2110/2510 Software Design Software Design for SE September 17, 2008 2 3 Department of Computer Science The Australian National University 4 18.1 18.2 GoF Structural

More information

Design Patterns V Structural Design Patterns, 2

Design Patterns V Structural Design Patterns, 2 Structural Design Patterns, 2 COMP2110/2510 Software Design Software Design for SE September 17, 2008 Department of Computer Science The Australian National University 19.1 1 2 Formal 3 Formal 4 Formal

More information

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D.

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D. Software Design Patterns Jonathan I. Maletic, Ph.D. Department of Computer Science Kent State University J. Maletic 1 Background 1 Search for recurring successful designs emergent designs from practice

More information

Topics in Object-Oriented Design Patterns

Topics in Object-Oriented Design Patterns Software design Topics in Object-Oriented Design Patterns Material mainly from the book Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides; slides originally by Spiros Mancoridis;

More information

Design Patterns Reid Holmes

Design Patterns Reid Holmes Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes GoF design patterns $ %!!!! $ "! # & Pattern vocabulary Shared vocabulary

More information

SDC Design patterns GoF

SDC Design patterns GoF SDC Design patterns GoF Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating

More information

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester Design Patterns Comp2110 Software Design Department of Computer Science Australian National University Second Semester 2005 1 Design Pattern Space Creational patterns Deal with initializing and configuring

More information

SOFTWARE PATTERNS. Joseph Bonello

SOFTWARE PATTERNS. Joseph Bonello SOFTWARE PATTERNS Joseph Bonello MOTIVATION Building software using new frameworks is more complex And expensive There are many methodologies and frameworks to help developers build enterprise application

More information

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.)

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.) Design Pattern CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.) A. Design Pattern Design patterns represent the best practices used by experienced

More information

Design Patterns in C++

Design Patterns in C++ Design Patterns in C++ Structural Patterns Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa March 23, 2011 G. Lipari (Scuola Superiore Sant Anna) Structural patterns March

More information

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011 Design Patterns Lecture 1 Manuel Mastrofini Systems Engineering and Web Services University of Rome Tor Vergata June 2011 Definition A pattern is a reusable solution to a commonly occurring problem within

More information

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns EPL 603 TOPICS IN SOFTWARE ENGINEERING Lab 6: Design Patterns Links to Design Pattern Material 1 http://www.oodesign.com/ http://www.vincehuston.org/dp/patterns_quiz.html Types of Design Patterns 2 Creational

More information

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich CSCD01 Engineering Large Software Systems Design Patterns Joe Bettridge Winter 2018 With thanks to Anya Tafliovich Design Patterns Design patterns take the problems consistently found in software, and

More information

Dr. Xiaolin Hu. Review of last class

Dr. Xiaolin Hu. Review of last class Review of last class Design patterns Creational Structural Behavioral Abstract Factory Builder Factory Singleton etc. Adapter Bridge Composite Decorator Façade Proxy etc. Command Iterator Observer Strategy

More information

An Introduction to Patterns

An Introduction to Patterns An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1 What is a Pattern? - 1 Work on software development patterns stemmed from work on patterns from building architecture

More information

Creational Patterns. Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU)

Creational Patterns. Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU) Creational Patterns Creational Patterns Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU) Factory Method (FM) Intent: Define an interface for creating an object, but

More information

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming Goals of Lecture Lecture 27: OO Design Patterns Cover OO Design Patterns Background Examples Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2001 April 24, 2001 Kenneth

More information

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern Think of drawing/diagramming editors ECE450 Software Engineering II Drawing/diagramming editors let users build complex diagrams out of simple components The user can group components to form larger components......which

More information

THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS

THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS LOGISTICS HW3 due today HW4 due in two weeks 2 IN CLASS EXERCISE What's a software design problem you've solved from an idea you learned from someone else?

More information

Design Pattern and Software Architecture: IV. Design Pattern

Design Pattern and Software Architecture: IV. Design Pattern Design Pattern and Software Architecture: IV. Design Pattern AG Softwaretechnik Raum E 3.165 Tele.. 60-3321 hg@upb.de IV. Design Pattern IV.1 Introduction IV.2 Example: WYSIWYG Editor Lexi IV.3 Creational

More information

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico Modellistica Medica Maria Grazia Pia INFN Genova Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico 2002-2003 Lezione 9 OO modeling Design Patterns Structural Patterns Behavioural Patterns

More information

administrivia today UML start design patterns Tuesday, September 28, 2010

administrivia today UML start design patterns Tuesday, September 28, 2010 administrivia Assignment 2? promise to get past assignment 1 back soon exam on monday review slides are posted your responsibility to review covers through last week today UML start design patterns 1 Unified

More information

Design for change. You should avoid

Design for change. You should avoid Design patterns Sources Cours de Pascal Molli «A System of Pattern» Bushmann et All «Design Patterns» Gamma et All (GoF) «Applying UML and Patterns» Larman "Design Patterns Java Workbook" Steven John Metsker

More information

The Strategy Pattern Design Principle: Design Principle: Design Principle:

The Strategy Pattern Design Principle: Design Principle: Design Principle: Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design

More information

Laboratorio di Progettazione di Sistemi Software Design Pattern Creazionali. Valentina Presutti (A-L) Riccardo Solmi (M-Z)

Laboratorio di Progettazione di Sistemi Software Design Pattern Creazionali. Valentina Presutti (A-L) Riccardo Solmi (M-Z) Laboratorio di Progettazione di Sistemi Software Design Pattern Creazionali Valentina Presutti (A-L) Riccardo Solmi (M-Z) Indice degli argomenti Catalogo di Design Patterns creazionali: Abstract Factory

More information

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar Design Patterns MSc in Communications Software Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Idioms and Design Patterns. Martin Skogevall IDE, Mälardalen University

Idioms and Design Patterns. Martin Skogevall IDE, Mälardalen University Idioms and Design Patterns Martin Skogevall IDE, Mälardalen University 2005-04-07 Acronyms Object Oriented Analysis and Design (OOAD) Object Oriented Programming (OOD Software Design Patterns (SDP) Gang

More information

Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns

Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns Today we are going to talk about an important aspect of design that is reusability of design. How much our old design

More information

COSC 3351 Software Design. Design Patterns Structural Patterns (I)

COSC 3351 Software Design. Design Patterns Structural Patterns (I) COSC 3351 Software Design Design Patterns Structural Patterns (I) Spring 2008 Purpose Creational Structural Behavioral Scope Class Factory Method Adaptor(class) Interpreter Template Method Object Abstract

More information

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico Modellistica Medica Maria Grazia Pia INFN Genova Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico 2002-2003 Lezione 8 OO modeling Design Patterns Introduction Creational Patterns Software

More information

Design Patterns Reid Holmes

Design Patterns Reid Holmes Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes GoF design patterns $ %!!!! $ "! # & Pattern vocabulary Shared vocabulary

More information

Design Pattern- Creational pattern 2015

Design Pattern- Creational pattern 2015 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are created composed represented Encapsulates knowledge about which concrete classes the system uses Hides

More information

Object-Oriented Oriented Programming

Object-Oriented Oriented Programming Object-Oriented Oriented Programming Composite Pattern CSIE Department, NTUT Woei-Kae Chen Catalog of Design patterns Creational patterns Abstract Factory, Builder, Factory Method, Prototype, Singleton

More information

Composite Pattern. IV.4 Structural Pattern

Composite Pattern. IV.4 Structural Pattern IV.4 Structural Pattern Motivation: Compose objects to realize new functionality Flexible structures that can be changed at run-time Problems: Fixed class for every composition is required at compile-time

More information

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns? What is a Pattern? Lecture 40: Design Patterns CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki "Each pattern describes a problem which occurs over and over again in our environment, and then describes

More information

Last Lecture. Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/ Spring Semester, 2005

Last Lecture. Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/ Spring Semester, 2005 1 Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/6448 - Spring Semester, 2005 2 Last Lecture Design Patterns Background and Core Concepts Examples

More information

Object-Oriented Concepts and Design Principles

Object-Oriented Concepts and Design Principles Object-Oriented Concepts and Design Principles Signature Specifying an object operation or method involves declaring its name, the objects it takes as parameters and its return value. Known as an operation

More information

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich CSCD01 Engineering Large Software Systems Design Patterns Joe Bettridge Winter 2018 With thanks to Anya Tafliovich Design Patterns Design patterns take the problems consistently found in software, and

More information

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011 Design Patterns Lecture 2 Manuel Mastrofini Systems Engineering and Web Services University of Rome Tor Vergata June 2011 Structural patterns Part 2 Decorator Intent: It attaches additional responsibilities

More information

Lecture 17: Patterns Potpourri. Copyright W. Howden 1

Lecture 17: Patterns Potpourri. Copyright W. Howden 1 Lecture 17: Patterns Potpourri Copyright W. Howden 1 GOF Patterns GOF: Gamma, Helm, Johnson, Vlissides Design Patterns, Addison Wesley, 1995 Patterns we have seen so far Creational Patterns e.g. Factory,

More information

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently. Gang of Four Software Design Patterns with examples STRUCTURAL 1) Adapter Convert the interface of a class into another interface clients expect. It lets the classes work together that couldn't otherwise

More information

Last Lecture. Lecture 26: Design Patterns (part 2) State. Goals of Lecture. Design Patterns

Last Lecture. Lecture 26: Design Patterns (part 2) State. Goals of Lecture. Design Patterns Lecture 26: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2003 Last Lecture Design Patterns Background and Core Concepts Examples Singleton,

More information

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued) MBSE - 2.1 Design Patterns and Architecture 1 2.1 Design Patterns and Architecture (continued) 1. Introduction 2. Model Construction 2.1 Design Patterns and Architecture 2.2 State Machines 2.3 Timed Automata

More information

Keywords: Abstract Factory, Singleton, Factory Method, Prototype, Builder, Composite, Flyweight, Decorator.

Keywords: Abstract Factory, Singleton, Factory Method, Prototype, Builder, Composite, Flyweight, Decorator. Comparative Study In Utilization Of Creational And Structural Design Patterns In Solving Design Problems K.Wseem Abrar M.Tech., Student, Dept. of CSE, Amina Institute of Technology, Shamirpet, Hyderabad

More information

Software Eningeering. Lecture 9 Design Patterns 2

Software Eningeering. Lecture 9 Design Patterns 2 Software Eningeering Lecture 9 Design Patterns 2 Patterns covered Creational Abstract Factory, Builder, Factory Method, Prototype, Singleton Structural Adapter, Bridge, Composite, Decorator, Facade, Flyweight,

More information

Design Patterns Lecture 2

Design Patterns Lecture 2 Design Patterns Lecture 2 Josef Hallberg josef.hallberg@ltu.se 1 Patterns covered Creational Abstract Factory, Builder, Factory Method, Prototype, Singleton Structural Adapter, Bridge, Composite, Decorator,

More information

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued) MBSE - 2.1 Design Patterns and Architecture 1 2.1 Design Patterns and Architecture (continued) 1. Introduction 2. Model Construction 2.1 Design Patterns and Architecture 2.2 State Machines 2.3 Abstract

More information

Design Pattern: Composite

Design Pattern: Composite Design Pattern: Composite Intent Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Motivation

More information

Creational Design Patterns

Creational Design Patterns Creational Design Patterns Creational Design Patterns Structural Design Patterns Behavioral Design Patterns GoF Design Pattern Categories Purpose Creational Structural Behavioral Scope Class Factory Method

More information

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

LABORATORY 1 REVISION

LABORATORY 1 REVISION UTCN Computer Science Department Software Design 2012/2013 LABORATORY 1 REVISION ================================================================== I. UML Revision This section focuses on reviewing the

More information

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1 What is a Design Pattern? Each pattern Describes a problem which occurs over and over again in our environment,and then describes the core of the problem Novelists, playwrights and other writers rarely

More information

The Design Patterns Matrix From Analysis to Implementation

The Design Patterns Matrix From Analysis to Implementation The Design Patterns Matrix From Analysis to Implementation This is an excerpt from Shalloway, Alan and James R. Trott. Design Patterns Explained: A New Perspective for Object-Oriented Design. Addison-Wesley

More information

Design Patterns. An introduction

Design Patterns. An introduction Design Patterns An introduction Introduction Designing object-oriented software is hard, and designing reusable object-oriented software is even harder. Your design should be specific to the problem at

More information

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG.

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG. Comp435 Object-Oriented Design Week 11 Computer Science PSU HBG 1 Define an interface for creating an object Let subclasses decide which class to instantiate Defer instantiation to subclasses Avoid the

More information

Facade and Adapter. Comp-303 : Programming Techniques Lecture 19. Alexandre Denault Computer Science McGill University Winter 2004

Facade and Adapter. Comp-303 : Programming Techniques Lecture 19. Alexandre Denault Computer Science McGill University Winter 2004 Facade and Adapter Comp-303 : Programming Techniques Lecture 19 Alexandre Denault Computer Science McGill University Winter 2004 March 23, 2004 Lecture 19 Comp 303 : Facade and Adapter Page 1 Last lecture...

More information

Information systems modelling UML and service description languages

Information systems modelling UML and service description languages Internet Engineering Tomasz Babczyński, Zofia Kruczkiewicz Tomasz Kubik Information systems modelling UML and service description languages Overview of design patterns for supporting information systems

More information

Adapter Pattern Structural

Adapter Pattern Structural Adapter Pattern Structural Intent» Convert the interface of a class into a different interface that a client expects.» Lets classes work together that otherwise could not Adapter-1 Class Adapter Motivation

More information

Object Oriented Paradigm

Object Oriented Paradigm Object Oriented Paradigm Ming-Hwa Wang, Ph.D. Department of Computer Engineering Santa Clara University Object Oriented Paradigm/Programming (OOP) similar to Lego, which kids build new toys from assembling

More information

Design Patterns. Claus Jensen

Design Patterns. Claus Jensen Design Patterns Claus Jensen What is a Design Pattern? A design pattern Abstracts a recurring design structure Distils design experience Promotes reuse of design and code Gives an opportunity to see how

More information

An Introduction to Patterns

An Introduction to Patterns An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1 What is a Pattern? Patterns are intended to capture the best available software development experiences in the

More information

Reuse at Design Level: Design Patterns

Reuse at Design Level: Design Patterns Reuse at Design Level: Design Patterns CS 617- Lecture 17 Mon. 17 March 2008 3:30-5:00 pm Rushikesh K. Joshi Department of Computer Sc. & Engg. Indian Institute of Technology, Bombay Mumbai - 400 076 Reuse

More information

Summary of the course lectures

Summary of the course lectures Summary of the course lectures 1 Components and Interfaces Components: Compile-time: Packages, Classes, Methods, Run-time: Objects, Invocations, Interfaces: What the client needs to know: Syntactic and

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

Exam in TDDB84: Design Patterns,

Exam in TDDB84: Design Patterns, Exam in TDDB84: Design Patterns, 2014-10-24 14-18 Information Observe the following, or risk subtraction of points: 1) Write only the answer to one task on one sheet. Use only the front side of the sheets

More information

Design Patterns. SE3A04 Tutorial. Jason Jaskolka

Design Patterns. SE3A04 Tutorial. Jason Jaskolka SE3A04 Tutorial Jason Jaskolka Department of Computing and Software Faculty of Engineering McMaster University Hamilton, Ontario, Canada jaskolj@mcmaster.ca November 18/19, 2014 Jason Jaskolka 1 / 35 1

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

CS342: Software Design. November 21, 2017

CS342: Software Design. November 21, 2017 CS342: Software Design November 21, 2017 Runnable interface: create threading object Thread is a flow of control within a program Thread vs. process All execution in Java is associated with a Thread object.

More information

Lecture 20: Design Patterns II

Lecture 20: Design Patterns II Lecture 20: Design Patterns II Software System Design and Implementation ITCS/ITIS 6112/8112 001 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte Nov.

More information

David Talby March 21, 2006

David Talby March 21, 2006 David Talby Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor Documented Proved Design Experience Finding the right classes Finding them faster Common

More information

Design Patterns. CSE870: Advanced Software Engineering (Design Patterns): Cheng

Design Patterns. CSE870: Advanced Software Engineering (Design Patterns): Cheng Design Patterns Acknowledgements Materials based on a number of sources D. Levine and D. Schmidt. Helm Gamma et al S. Konrad Motivation Developing software is hard Designing reusable software is more challenging

More information

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Iterator Pattern George Blankenship

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Iterator Pattern George Blankenship CSCI 253 Object Oriented Design: Iterator Pattern George Blankenship George Blankenship 1 Creational Patterns Singleton Abstract factory Factory Method Prototype Builder Overview Structural Patterns Composite

More information

Software Design COSC 4353/6353 D R. R A J S I N G H

Software Design COSC 4353/6353 D R. R A J S I N G H Software Design COSC 4353/6353 D R. R A J S I N G H Creational Design Patterns What are creational design patterns? Types Examples Structure Effects Creational Patterns Design patterns that deal with object

More information

Tuesday, October 4. Announcements

Tuesday, October 4. Announcements Tuesday, October 4 Announcements www.singularsource.net Donate to my short story contest UCI Delta Sigma Pi Accepts business and ICS students See Facebook page for details Slide 2 1 Design Patterns Design

More information

What is Design Patterns?

What is Design Patterns? Paweł Zajączkowski What is Design Patterns? 1. Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. 2. In other words,

More information

ADAPTER. Topics. Presented By: Mallampati Bhava Chaitanya

ADAPTER. Topics. Presented By: Mallampati Bhava Chaitanya ADAPTER Presented By: Mallampati Bhava Chaitanya Topics Intent Motivation Applicability Structure Participants & Collaborations Consequences Sample Code Known Uses Related Patterns Intent Convert the interface

More information

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

More information

Introduction to Software Engineering: Object Design I Reuse & Patterns

Introduction to Software Engineering: Object Design I Reuse & Patterns Introduction to Software Engineering: Object Design I Reuse & Patterns John T. Bell Department of Computer Science University of Illinois, Chicago Based on materials from Bruegge & DuToit 3e, Chapter 8,

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

INTERNAL ASSESSMENT TEST III Answer Schema

INTERNAL ASSESSMENT TEST III Answer Schema INTERNAL ASSESSMENT TEST III Answer Schema Subject& Code: Object-Oriented Modeling and Design (15CS551) Sem: V ISE (A & B) Q. No. Questions Marks 1. a. Ans Explain the steps or iterations involved in object

More information

Design Patterns! Acknowledgements!

Design Patterns! Acknowledgements! Design Patterns! Acknowledgements! Materials based on a number of sources! D. Levine and D. Schmidt!. Helm! Gamma et al! S. Konrad! (Cheng) 1 Motivation! Developing software is hard! Designing reusable

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Object-Oriented Oriented Programming Command Pattern. CSIE Department, NTUT Woei-Kae Chen

Object-Oriented Oriented Programming Command Pattern. CSIE Department, NTUT Woei-Kae Chen Object-Oriented Oriented Programming Command Pattern CSIE Department, NTUT Woei-Kae Chen Command: Intent Encapsulate a request as an object thereby letting you parameterize clients with different requests

More information

Design Patterns. GoF design patterns catalog

Design Patterns. GoF design patterns catalog Design Patterns GoF design patterns catalog OMT notations - classes OMT notation - relationships Inheritance - triangle Aggregation - diamond Acquaintance keeps a reference solid line with arrow Creates

More information

The Factory Method Pattern

The Factory Method Pattern The Factory Method Pattern Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses. 1 The

More information

Brief Note on Design Pattern

Brief Note on Design Pattern Brief Note on Design Pattern - By - Channu Kambalyal channuk@yahoo.com This note is based on the well-known book Design Patterns Elements of Reusable Object-Oriented Software by Erich Gamma et., al.,.

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

Department of Information Technology

Department of Information Technology LECTURE NOTES ON DESIGN PATTERNS B.TECH IV-I JNTUH(R15) Ms. B. REKHA Assistant Professor Department of Information Technology INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal 500 043, Hyderabad

More information

The GoF Design Patterns Reference

The GoF Design Patterns Reference The GoF Design Patterns Reference Version.0 / 0.0.07 / Printed.0.07 Copyright 0-07 wsdesign. All rights reserved. The GoF Design Patterns Reference ii Table of Contents Preface... viii I. Introduction....

More information

Slide 1. Design Patterns. Prof. Mirco Tribastone, Ph.D

Slide 1. Design Patterns. Prof. Mirco Tribastone, Ph.D Slide 1 Design Patterns Prof. Mirco Tribastone, Ph.D. 22.11.2011 Introduction Slide 2 Basic Idea The same (well-established) schema can be reused as a solution to similar problems. Muster Abstraktion Anwendung

More information

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1 Design Principles Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques 2-1 Data Structures Data Structure - A systematic way of organizing and accessing

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY

EINDHOVEN UNIVERSITY OF TECHNOLOGY EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics & Computer Science Exam Programming Methods, 2IP15, Wednesday 17 April 2013, 09:00 12:00 TU/e THIS IS THE EXAMINER S COPY WITH (POSSIBLY INCOMPLETE)

More information

Coordination Patterns

Coordination Patterns Coordination Patterns 1. Coordination Patterns Design Patterns and their relevance for Coordination Oscar Nierstrasz Software Composition Group Institut für Informatik (IAM) Universität Bern oscar@iam.unibe.ch

More information

Design Patterns Revisited

Design Patterns Revisited CSC 7322 : Object Oriented Development J Paul Gibson, A207 paul.gibson@int-edu.eu http://www-public.it-sudparis.eu/~gibson/teaching/csc7322/ Design Patterns Revisited /~gibson/teaching/csc7322/l13-designpatterns-2.pdf

More information

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich CSCD01 Engineering Large Software Systems Design Patterns Joe Bettridge Winter 2018 With thanks to Anya Tafliovich Design Patterns Design patterns take the problems consistently found in software, and

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information