1.28k likes | 1.44k Views
CENG 217 Object Oriented Design Lecture 5. Doç. Dr. Hal û k Gümüşkaya haluk @ gumuskaya.com / haluk@fatih.edu.tr http://www. gumuskaya.com Computing Engineering Department Fatih University. Saturday, October 25, 2014. Patterns and GUI Programming. Lecture Outline.
E N D
CENG 217Object Oriented DesignLecture 5 Doç. Dr. Halûk Gümüşkaya haluk@gumuskaya.com / haluk@fatih.edu.trhttp://www.gumuskaya.com Computing Engineering Department Fatih University Saturday, October 25, 2014
Lecture Outline • The ITERATOR as a Pattern • The Pattern Concept and Introduction to GoF Design Patterns • The OBSERVER Pattern • Layout Managers and the STRATEGY Pattern • Components, Containers, and the COMPOSITE Pattern • Scroll Bars and the DECORATOR Pattern • How to Recognize Patterns • Putting Patterns to Work
List Iterators LinkedList<String> list = . . .;ListIterator<String> iterator = list.listIterator();while (iterator.hasNext()){ String current = iterator.next(); . . .} • Why iterators? Classical List Data Structure • Traverse links directly Link currentLink = list.head;while (currentLink != null){ Object current = currentLink.data; currentLink = currentLink.next;} • Exposes implementation • Error-prone
High-Level View of Data Structures • Queue • Array with random access • List • ???
List with Cursor for (list.reset(); list.hasNext(); list.next()){ Object x = list.get(); . . .} • Disadvantage: Only one cursor per list , debugging!!! • Iterator is superior concept
The ITERATOR as a Pattern • The Pattern Concept and Introduction to GoF Design Patterns • The OBSERVER Pattern • Layout Managers and the STRATEGY Pattern • Components, Containers, and the COMPOSITE Pattern • Scroll Bars and the DECORATOR Pattern • How to Recognize Patterns • Putting Patterns to Work
What is a Pattern? History: Architectural Patterns • Current use comes from the work of the architect Christopher Alexander. • Alexander studied ways to improve the process of designing buildings and urban areas. • He formulated over 250 patterns for architectural designs. C. Alexander et al., A Pattern Language: Towns, Buildings, Construction, Oxford University Press, 1977. • Patterns can be applied to many different areas of human endeavor, including software development… There are patterns of success, and patterns of failure…
The Pattern Concept: Context, Problem and Solution • “Each pattern is a three-part rule, which expresses a relation between a certain context, a problem and a solution.” • Hence, the common definition of a pattern: “A solution to a problem in a context.” • Each pattern has • a short name • a brief description of the context • a lengthy description of the problem • a prescription for the solution
Short Passages Pattern • Context "...Long, sterile corridors set the scene for everything bad about modern architecture..." • Problem a lengthy description of the problem, including • a depressing picture • issues of light and furniture • research about patient anxiety in hospitals • research that suggests that corridors over 50 ft are considered uncomfortable
Short Passages Pattern Solution • Keep passages short. Make them as much like rooms as possible, with carpets or wood on the floor, furniture, bookshelves, beautiful windows. Make them generous in shape and always give them plenty of light; the best corridors and passages of all are those which have windows along an entire wall.
Why Patterns? “Designing object-oriented software is hard and designingreusable object-oriented software is even harder.”- Erich Gamma Experienced designers reuse solutions that have worked in thepast. Well-structured object-oriented systems have recurring patterns ofclasses and objects. Knowledge of the patterns that have worked in the past allows adesigner to be more productive and the resulting designs to bemore flexible and reusable.
Benefits of Design Patterns Capture expertise and make it accessible to non-experts in astandard form Facilitate communication among developers by providing acommon language Make it easier to reuse successful designs and avoid alternativesthat diminish reusability Facilitate design modifications Improve design documentation Improve design understandability
Drawbacks of Design Patterns Patternsdonotleadtodirectcodereuse Patterns are deceptively simple Teamsmaysufferfrompatternoverload Patternsarevalidatedbyexperienceanddiscussionratherthanbyautomatedtesting Integratingpatternsintoasoftwaredevelopmentprocessisa human-intensive activity
Software Patterns History 1987 - Cunningham and Beck used Alexander’s ideas to developa small pattern language for Smalltalk 1990 - The Gang of Four (Gamma, Helm, Johnson and Vlissides)begin work compiling a catalog of design patterns 1991 - Bruce Anderson gives first Patterns Workshop atOOPSLA 1993 - Kent Beck and Grady Booch sponsor the first meeting ofwhat is now known as the Hillside Group 1994 - First Pattern Languages of Programs (PLoP) conference 1995 -The Gang of Four (GoF) publish the Design Patterns book
GoF (Gang of Four) Design Patterns Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (Gang of Four – GoF), Design Patterns: Elements of Reusable Object-Oriented Software, Addison Wesley, 1995. There are 23 design patterns given in this book. They are classified into 3 purposes: Creational, Structural, and Behavioral.
GoF Notation The GoF book uses the Object Modeling Technique (OMT)notation for class and object diagrams: • Notational issues • Attributes come after the Operations • Associations are called acquaintances • Multiplicities are shown as solid circles • Inheritance shown as triangle • Dashed line: Instantiation Association (Class can instantiate objects of associated class) (In UML it denotes a dependency • UML Note is called Dogear box (connected by dashed line to class operation): Pseudo-code implementation of operation
UML Notation for Design Patterns We will use UML in design patterns.
Creational Patterns (5 patterns) • FactoryMethod (OODP Chp10) – Method in a derived class creates associates • AbstractFactory – Factory for building related objects • Builder – Factory for building complex objects incrementally • Prototype – Factory for cloning new instances from a prototype • Singleton (OODP Chp10) – Factory for a singular (sole) instance
Structural Patterns (7 patterns) • Adapter (OODP Chp10) – Translator adapts a server interface for a client • Bridge – Abstraction for binding one of many implementations • Composite (OODP Chp5) – Structure for building recursive aggregations • Decorator (OODP Chp5) – Decorator extends an object transparently • Facade – Facade simplifies the interface for a subsystem • Flyweight – Many fine-grained objects shared efficiently • Proxy (OODP Chp10) – One object approximates another
Behavioral Patterns (11 patterns) • ChainofResponsibility – Request delegated to the responsible service provider • Command (OODP Chp10) – Request as first-class object • Interpreter – Language interpreter for a small grammar • Iterator (OODP Chp5) – Aggregate elements are accessed sequentially • Mediator – Mediator coordinates interactions between its associates • Memento – Snapshot captures and restores object states privately
Behavioral Patterns (continued) • Observer (OODP Chp5) – Dependents update automatically when a subject changes • State – Object whose behavior depends on its state • Strategy (OODP Chp5) – Abstraction for selecting one of many algorithms • TemplateMethod – Algorithm with some steps supplied by a derived class • Visitor (OODP Chp10) – Operations applied to elements of an heterogeneous object structure
An Example: Iterator Pattern Context • An aggregate object contains element objects • Clients need access to the element objects • The aggregate object should not expose its internal structure • Multiple clients may want independent access Solution • Define an iterator that fetches one element at a time • Each iterator object keeps track of the position of the next element • If there are several aggregate/iterator variations, it is best if the aggregate and iterator classes realize common interface types. Then the client only needs to know the interface types, not the concrete classes.
Iterator Pattern • Names in pattern are examples • Names differ in each occurrence of pattern
The ITERATOR as a Pattern • The Pattern Concept and Introduction to GoF Design Patterns • The OBSERVER Pattern • Layout Managers and the STRATEGY Pattern • Components, Containers, and the COMPOSITE Pattern • Scroll Bars and the DECORATOR Pattern • How to Recognize Patterns • Putting Patterns to Work
Model/View/Controller • Some programs have multiple editable views • Example: HTML Editor • WYSIWYG view • structure view • source view • Editing one view updates the other • Updates seem instantaneous
Windows An example of MVC architecture: The “model” is the filename dp3.ppt. One “view” is a window titled CENG 534 Design Patterns, which displays the contents of a folder containing the file dp3.ppt. The other “view” is window called dp3.ppt Properties, which displays information related to the file. If the file name is changed, both views are updated by the “controller”.
Model/View/Controller • Model: data structure, no visual representation • Views: visual representations • Controllers: user interaction • Views/controllers update model • Model tells views that data has changed • Views redraw themselves • MVC is an Architectural Pattern and is not a GoF Pattern. But it is based on the Observer (Model/View) GoF pattern.
Observer Pattern • Model notifies views when something interesting happens • Button notifies action listeners when something interesting happens • Views attach themselves to model in order to be notified • The View(s) display the Model and is notified (via a subscribe/notify protocol) whenever the Model is changed. • Action listeners attach themselves to button in order to be notified • Generalize:Observers attach themselves to subject • Observer is a behavioral GoF Pattern.
Observer Pattern Context • An object, called the subject, is source of events • One or more observer objects want to be notified when such an event occurs. Solution • Define an observer interface type. All concrete observers implement it. • The subject maintains a collection of observers. • The subject supplies methods for attaching and detaching observers. • Whenever an event occurs, the subject notifies all observers.
Observer Pattern • Java 1.1 introduced a new GUI event model based on the Observer Pattern • GUI components which can generate GUI events are called event sources. • Objects that want to be notified of GUI events are called event (action) listeners. • Event generation is also called firing the event. • Comparison to the Observer Pattern: Subject => event source (Example: JButton)Observer => Action ListenerConcreteObserver => Action Listener implementation • For an event listener to be notified of an event, it must first register with the event source.
Observer Pattern (From GoF Books) • Intent • Define a one-to-many dependency between objects so that when one objectchanges state, all its dependents are notified and updated automatically. • Also Known As • Dependents, Publish-Subscribe, Model-View. • Motivation • The need to maintain consistency between related objects without makingclasses tightly coupled.
Applicability • Use the Observer pattern in any of the following situations: • When an abstraction has two aspects, one dependent on the other.Encapsulating these aspects in separate objects lets you vary and reusethem independently. • When a change to one object requires changing others • When an object should be able to notify other objects without makingassumptions about those objects
The Elements of Observer Pattern Participants • Subject • Keeps track of its observers • Provides an interface for attaching and detaching Observer objects • Observer • Defines an interface for update notification • ConcreteSubject • The object being observed • Stores state of interest to ConcreteObserver objects • Sends a notification to its observers when its state changes • ConcreteObserver • The observing object • Stores state that should stay consistent with the subject's • Implements the Observer update interface to keep its state consistent with thesubject's
Consequences • Benefits • Minimal coupling between the Subject and the Observer • Can reuse subjects without reusing their observers and vice versa • Observers can be added without modifying the subject • All subject knows is its list of observers • Subject does not need to know the concrete class of an observer, just thateach observer implements the update interface • Subject and observer can belong to different abstraction layers • Support for event broadcasting • Subject sends notification to all subscribed observers • Observers can be added/removed at any time • Liabilities • Possible cascading of notifications • Observers are not necessarily aware of each other and must be carefulabout triggering updates • Simple update interface requires observers to deduce changed item
Sample Code, Known Uses and Related Patterns • Sample Code • We'll see some Java soon! • Known Uses • Smalltalk Model/View/Controller user interface framework • Model = Subject • View = Observer • Controller is whatever object changes the state of the subject • Related Patterns • Mediator • To encapsulate complex update semantics
Using Design Patterns Templates in Together for Eclipse Architect 2006 • Use Class By Templete or choose any class on the diagram and apply one of GoF Design Patterns: