1 / 33

Design Patterns

Design Patterns ; Gamma, Helm, Johnson, Vlissides. Reference:. Design Patterns. Contents. Terminology in object-oriented design. Mechanisms for reuse. Designing for change. Categorizing and selecting design patterns. Terminology. Object Interface. a. Signature of a method. Toolkits.

contrerasj
Download Presentation

Design Patterns

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

E N D

Presentation Transcript


  1. Design Patterns; Gamma, Helm, Johnson, Vlissides Reference: Design Patterns Contents • Terminology in object-oriented design • Mechanisms for reuse • Designing for change • Categorizing and selecting design patterns

  2. Terminology • Object Interface a. Signature of a method • Toolkits • Frameworks • Design Patterns

  3. Class diagram Name attributes Object Interface Every method in the class has its own unique signature return_type name (parameter types) The set of all signatures defined by an object’s methods or operations is called the object interface. methods This interface characterizes the complete set of requests that can be sent to the object.

  4. ClassA int metod1(int param); void resize( ); ClassB intmetod1(intparam); int metod1(int param); void resize( ); void resize( ); Specifying Object Interfaces Signature of a method: • name • parameters • return type Interface Possible message recipients

  5. Circle Shape double area( ) ; void resize(int scale) ; virtualdouble area( ) = 0; void draw( ) ; virtualvoid draw( ) = 0; virtualvoid resize(int scale) = 0; Rectangle double area( ) ; void draw( ) ; void resize(int scale) ; Implementation of an Interface in C++ Interface provided by an abstract class Concrete realizations receive the messages

  6. Class Hierarchy Shape Rectangle Circle Square Messages directed to aShapeobject can be received by instances of any of these concrete classes.

  7. Toolkits A toolkit is a set of related and reusable classes designed to provide general-purpose functionality. – Gamma et al. Examples: Collection classes: Vector, Stack, Queue, List, etc: Found in libraries such as java.util or the C++ STL The Java or C++ stream library

  8. Frameworks A framework is a set of cooperating classes that make up a reusable design for a specific class of software. – Gamma, et al. The framework dictates the architecture of your application. It captures the design decisions that are common to the domain of the application. It establishes the partitioning into classes and objects and the pattern of collaboration between objects. Frameworks promote designreuse Example: the java awt and swing packages

  9. Design Patterns Patterns capture solutions to particular design problems. They provide for the reuse of successful designs. Incorporate design experience. A design pattern is like a template that can be applied in many different situations. A design pattern provides an abstract description of a design problem and how a general arrangement of elements (classes and objects) solves it. – Gamma et al.

  10. Design Patterns Design Patterns emphasize “design for maintainability”. Good design not only addresses the current problem, but also anticipates the need for future additions and modifications.

  11. Elements of a Design Pattern Pattern Name Names allow the designer to work at a higher level of abstraction. Names make it easier to talk about and think about designs. Description of the problem Describes the problem and its context. The Solution Describes the classes that make up the design, their relationships, and collaborations. The Consequences The results and tradeoffs of applying the pattern.

  12. Purpose Design Pattern Aspects that can vary Creational Abstract Factory Families of product objects Builder Creation of a composite object Factory Method Subclass of object instantiated Structural Adapter Interface to an object Facade Interface to a subsystem Flyweight Storage costs of objects Proxy How an object is accessed Behavioral Command When & how a request is fulfilled Iterator Traversal of elements in an aggregate Categories of Design Patterns {Partial listing}

  13. Notation B A A B ClassName Implementation pseudocode class method o Symbol Meaning Aggregation Object A instantiates B B is a subclass of A Comment box

  14. Iterator Pattern Intent Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. • Supports multiple traversals of aggregate objects. • Provides a uniform interface for traversing different aggregate structures (it supports polymorphic iteration).

  15. Aggregate Iterator Client first( ) next( ) isDone( ) currentItem( ) ConcreteAggregate ConcreteIterator createIterator( ) return new ConcreteIterator(this) Iterator Pattern Structure createIterator( ) //client code Aggregate myList = new ConcreteAggregate( ); Iterator itr = myList.createIterator( );

  16. Iterator Pattern Participants • Iterator -- defines an interface for accessing and traversing elements • ConcreteIterator -- 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 -- implements the Iterator creation interface to return an instance of the proper ConcreteIterator

  17. Iterator Pattern Consequences • It supports variations in the traversal of an aggregate. For example, code generation may traverse the parse tree inorder or preorder. Iterators make it easy to change the traversal. Just replace the iterator instance with a different one. • Iterators simplify the Aggregate interface. Iterator’s traversal interface obviates the need for a similar interface in Aggregate. • More than one traversal can be pending on an aggregate.

  18. Iterator Pattern Iterators in Java In object-oriented programming one distinguishes between the container object that holds data and an Iterator object that traverses the container and visits the data items. To use an Iterator perform the following steps: • Obtain an iterator from the Collection object (List) by using a method (in the interface) iterator( ). This method call returns an iterator object and sets it to read the first element in the list. • Get the next object in sequence with method next( ). • See if there are any more elements in the sequence with a call to hasNext( ). • You may remove the last item returned by the iterator from the list with a call to remove( )

  19. Iterator Pattern Iterator in Java -- in Java we have the following methods that implement the Design Pattern Iterator Iterator itr = containerObject.iterator( ); Implements the createIterator( ) in the Iterator Pattern itr.hasNext( ) Java implementation of isDone( ) Combines methods currentItem( ) and next( ) specified in the Pattern itr.next( )

  20. Iterator Pattern The method receives an iterator object as its argument withno distinction made about what collection produced it. Obtain an iterator from the ArrayList and pass it to the Printer Example of a polymorphic iterator With an iterator one can write generic methods to handle any collection publicclass Printer { publicstaticvoid printAll (Iterator e) { while (e.hasNext( ) ) System.out.print (e.next( ) + “ ” ); System.out.println( ); } publicclass FrogPond { publicstatic void main(String [ ] args) { ArrayList v = new ArrayList( ); for (int i = 0; i < args[0]; i++) v.add(new Frog(i)); Printer.printAll(v.iterator( )); } }

  21. Command Pattern Intent Encapsulate a request as an object letting you: • Parameterize clients with different requests • Queue or log requests • Support undo operations

  22. Command Client execute() Invoker ConcreteCommand Receiver execute() o action() state receiver_action() Command Pattern Structure

  23. Command Pattern Participants • Command -- declares an interface for executing an operation • ConcreteCommand -- defines a binding between a Receiver object and an action --implements execute() by invoking the corresponding operation(s) on Receiver • Client (Application) -- creates a ConcreteCommand object and sets its receiver • Invoker (Menuitem) --asks the command to carry out the request • Receiver (Document) --knows how to carry out the request. (Any class may serve as Receiver)

  24. aReceiver anInvoker aClient aCommand new Command add(aCommand) execute( ) action( ) Command Pattern Collaborations

  25. Command Pattern Collaborations • The Client creates a ConcreteCommand object and specifies its receiver. • An Invoker object stores the ConcreteCommand object. • The invoker issues a request by calling execute( ) on the command. When commands are undoable, ConcreteCommand stores state for undoing prior to invoking execute( ). • The ConcreteCommand object invokes operations on its receiver to carry out the request.

  26. Command Pattern 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. • Its easy to add new Commands, because you don’t have to change existing classes. • Commands can be assembled into a composite command.

  27. Menu MenuItem select( ); App Push Pop Command execute() execute( ) Stack item ask( ) S-> push(item) Invoker Abstract Command run( ) Receiver Concrete Commands Command Pattern Implemented in C++

  28. Using Command Pattern in Java Let’s redo the previous example in Java. The Command Design Pattern can be implemented within the framework provided in the swing classes. Inheritance Structure JMenu JMenuBar AbstractButton JMenuItem JRadioButtonMenuItem JComponent JPopupMenu JCheckBoxmenuItem Notice that a JMenu is itself a menu item. This allows one to place a submenu inside of another menu.

  29. Command Pattern in Java Extend class JMenuItem to pass in a Command object in the constructor, and add a method select( ) that calls the execute( ) method of the embedded command. class MyJMenuItem extends JMenuItem{ Command theOrder; public MyJMenuItem(String str, Command c) { super(str); theOrder = c; } public void select( ) { theOrder.execute( ); } }

  30. Command Pattern in Java In the application (JApplet) method actionPerformed( ) determines the source of the event (menu item selected) and executes its method select. public void actionPerformed(ActionEvent e) { MyJMenuItem theItem = (MyJMenuItem)(e.getSource( )); theItem.select( ); }

  31. Interface Command with (abstract) method execute Object Pop a concrete Command The Stack object that the Command directs is passed in as a parameter in the constructor Concrete Command objects override method execute( ) Command Pattern in Java Commands are OBJECTS that implement the Command interface. interface Command { public void execute( ); } class Pop implements Command{ Stack theStack; public Pop(Stack s) { theStack = s; } publicvoid execute( ) { theStack.pop( ); } }

  32. JMenu JMenuItem select( ); Push Pop Command execute() execute( ) Stack item ask( ) S-> push(item) Invoker Abstract Command JApplet run( ) Receiver Concrete Commands Command Pattern Implemented in Java

  33. Further Information about Design Patterns Design Patterns Home Page Links of particular interest: Doug Lea’s FAQ on Design Patterns Setting up a Design Pattern study group

More Related