Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CENG 217 Object Oriented Design Lecture 5 Doç. Dr. Halûk Gümüşkaya / Computing Engineering.

Similar presentations


Presentation on theme: "1 CENG 217 Object Oriented Design Lecture 5 Doç. Dr. Halûk Gümüşkaya / Computing Engineering."— Presentation transcript:

1 1 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, September 05, 2015

2 2 Patterns and GUI Programming

3 3 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work Lecture Outline

4 4 List Iterators LinkedList list =...; ListIterator iterator = list.listIterator(); while (iterator.hasNext()) { String current = iterator.next();... } u Why iterators? Classical List Data Structure u Traverse links directly Link currentLink = list.head; while (currentLink != null) { Object current = currentLink.data; currentLink = currentLink.next; } u Exposes implementation u Error-prone

5 5 High-Level View of Data Structures u Queue u Array with random access u List u ???

6 6 List with Cursor for (list.reset(); list.hasNext(); list.next()) { Object x = list.get();... } u Disadvantage: Only one cursor per list, debugging!!! u Iterator is superior concept

7 7 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

8 8 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…

9 9 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

10 10 Short Passages Pattern u Context "...Long, sterile corridors set the scene for everything bad about modern architecture..." u 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

11 11 Short Passages Pattern Solution u 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.

12 12 Why Patterns? “ Designing object-oriented software is hard and designing reusable object-oriented software is even harder.” - Erich Gamma Experienced designers reuse solutions that have worked in the past. Well-structured object-oriented systems have recurring patterns of classes and objects. Knowledge of the patterns that have worked in the past allows a designer to be more productive and the resulting designs to be more flexible and reusable.

13 13 Benefits of Design Patterns Capture expertise and make it accessible to non-experts in a standard form Facilitate communication among developers by providing a common language Make it easier to reuse successful designs and avoid alternatives that diminish reusability Facilitate design modifications Improve design documentation Improve design understandability

14 14 Drawbacks of Design Patterns Patterns do not lead to direct code reuse Patterns are deceptively simple Teams may suffer from pattern overload Patterns are validated by experience and discussion rather than by automated testing Integrating patterns into a software development process is a human-intensive activity

15 15 Software Patterns History 1987 - Cunningham and Beck used Alexander’s ideas to develop a 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 at OOPSLA 1993 - Kent Beck and Grady Booch sponsor the first meeting of what 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

16 16 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.

17 17 GoF Classification Of Design Patterns

18 18 GoF Essential Elements Of Design Patterns

19 19 GoF Pattern Template

20 20 GoF Pattern Template (Continued)

21 21 GoF Pattern Template (Continued)

22 22 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

23 23 GoF Notation Example

24 24 UML Notation for Design Patterns We will use UML in design patterns.

25 25 Creational Patterns (5 patterns) Factory Method (OODP Chp10) – Method in a derived class creates associates Abstract Factory – 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

26 26 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

27 27 Behavioral Patterns (11 patterns) Chain of Responsibility – 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

28 28 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 Template Method – Algorithm with some steps supplied by a derived class Visitor (OODP Chp10) – Operations applied to elements of an heterogeneous object structure

29 29 Relationships in GoF Patterns

30 30 An Example: Iterator Pattern Context 1.An aggregate object contains element objects 2.Clients need access to the element objects 3.The aggregate object should not expose its internal structure 4.Multiple clients may want independent access Solution 1.Define an iterator that fetches one element at a time 2.Each iterator object keeps track of the position of the next element 3.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.

31 31 Iterator Pattern

32 32 Iterator Pattern u Names in pattern are examples u Names differ in each occurrence of pattern Name in Design PatternActual Name (linked lists) AggregateList ConcreteAggregateLinkedList IteratorListIterator ConcreteIteratoranonymous class implementing ListIterator createIterator()listIterator() next() isDone()opposite of hasNext() currentItem()return value of hasNext()

33 33 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

34 34 Model/View/Controller u Some programs have multiple editable views u Example: HTML Editor WYSIWYG view structure view source view u Editing one view updates the other u Updates seem instantaneous

35 35 HTML Editor: MS FrontPage WYSIWYG view

36 36 MS FrontPage Source View

37 37 MS FrontPage Structure (Navigation) View

38 38 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”.

39 39 Model/View/Controller u Model: data structure, no visual representation u Views: visual representations u Controllers: user interaction u Views/controllers update model u Model tells views that data has changed u Views redraw themselves u MVC is an Architectural Pattern and is not a GoF Pattern. But it is based on the Observer (Model/View) GoF pattern.

40 40 Observer Pattern u Model notifies views when something interesting happens u Button notifies action listeners when something interesting happens u Views attach themselves to model in order to be notified u The View(s) display the Model and is notified (via a subscribe/notify protocol) whenever the Model is changed. u Action listeners attach themselves to button in order to be notified u Generalize: Observers attach themselves to subject u Observer is a behavioral GoF Pattern.

41 41 Observer Pattern Context 1.An object, called the subject, is source of events 2.One or more observer objects want to be notified when such an event occurs. Solution 1.Define an observer interface type. All concrete observers implement it. 2.The subject maintains a collection of observers. 3.The subject supplies methods for attaching and detaching observers. 4.Whenever an event occurs, the subject notifies all observers.

42 42 Observer Pattern u Java 1.1 introduced a new GUI event model based on the Observer Pattern u GUI components which can generate GUI events are called event sources. u Objects that want to be notified of GUI events are called event (action) listeners. u Event generation is also called firing the event. u Comparison to the Observer Pattern: Subject => event source (Example: JButton) Observer => Action Listener ConcreteObserver => Action Listener implementation u For an event listener to be notified of an event, it must first register with the event source.

43 43 Names in Observer Pattern Name in Design PatternActual Name (Swing buttons) SubjectJButton ObserverActionListener ConcreteObserverthe class that implements the ActionListener interface type attach()addActionListener() notify()actionPerformed()

44 44 Observer Pattern (From GoF Books) n Intent u Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. n Also Known As u Dependents, Publish-Subscribe, Model-View. n Motivation u The need to maintain consistency between related objects without making classes tightly coupled.

45 45 Applicability n Use the Observer pattern in any of the following situations: u When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. u When a change to one object requires changing others u When an object should be able to notify other objects without making assumptions about those objects

46 46 Structure (given in GoF DP Book)

47 47 The Elements of Observer Pattern Participants u Subject Keeps track of its observers Provides an interface for attaching and detaching Observer objects u Observer Defines an interface for update notification u ConcreteSubject The object being observed Stores state of interest to ConcreteObserver objects Sends a notification to its observers when its state changes u 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 the subject's

48 48 Consequences n Benefits u 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 that each observer implements the update interface Subject and observer can belong to different abstraction layers u Support for event broadcasting Subject sends notification to all subscribed observers Observers can be added/removed at any time n Liabilities u Possible cascading of notifications Observers are not necessarily aware of each other and must be careful about triggering updates u Simple update interface requires observers to deduce changed item

49 49 Sample Code, Known Uses and Related Patterns n Sample Code u We'll see some Java soon! n Known Uses u Smalltalk Model/View/Controller user interface framework Model = Subject View = Observer Controller is whatever object changes the state of the subject n Related Patterns u Mediator To encapsulate complex update semantics

50 50 Using Design Patterns Templates in Together for Eclipse Architect 2006 u Use Class By Templete or choose any class on the diagram and apply one of GoF Design Patterns:

51 51 Select Template and Specify Parameters

52 52 Observers and Observables Created by Together u Create Pattern Links: unchecked

53 53 Observers and Observables Created by Together u Create Pattern Links: Checked

54 54 Files Created by Together: Subject: Vehicle.java import java.util.ArrayList; import java.util.Iterator; /** * @role __Subject */ public class Vehicle { private ArrayList observers; /** * @link * @shapeType PatternLink * @pattern gof.Observer * @supplierRole Abstract Observer */ /* # private TrafficControl lnkTrafficControl; */ public void attach(TrafficControl observer) { observers.add(observer); } public void detach(TrafficControl observer) { observers.remove(observer); } public void notifyObservers() { Iterator it = observers.iterator(); while (it.hasNext()) { ((TrafficControl) it.next()).update(this); }

55 55 Concrete Subjects: Car, Truck, and Van /** * Stores state of interest to ConcreteObserver objects. * Sends a notification to its observers when its state changes. */ public class Car extends Vehicle { } /** * Stores state of interest to ConcreteObserver objects. * Sends a notification to its observers when its state changes. */ public class Truck extends Vehicle { } /** * Stores state of interest to ConcreteObserver objects. * Sends a notification to its observers when its state changes. */ public class Van extends Vehicle { }

56 56 Traffic Control Interface and Concrete Observers /** * @role __Observer */ public interface TrafficControl { /** * @link * @shapeType PatternLink * @pattern gof.Observer * @supplierRole Abstract Subject */ /*# private Vehicle lnkVehicle;*/ void update(Vehicle subject); } /** * Implements the Observer updating interface to keep * its state consistent with the subject's. */ public class HighwayPatrol implements TrafficControl { public void update(Vehicle subject) { //put your code here } /** * Implements the Observer updating interface to keep * its state consistent with the subject's. */ public class Sheriff implements TrafficControl { public void update(Vehicle subject) { //put your code here }

57 57 Java Implementation of Observer Pattern u We could implement the Observer pattern “from scratch” in Java u But Java provides the Observable/Observer classes as built-in support for the Observer pattern  The java.util.Observable class is the base Subject class. Any class that wants to be observed extends this class. Provides methods to add/delete observers Provides methods to notify all observers A subclass only needs to ensure that its observers are notified in the appropriate mutators Uses a Vector for storing the observer references  The java.util.Observer interface is the Observer interface. It must be implemented by any observer class.

58 58 The java.util.Observable Class u public Observable() Construct an Observable with zero Observers u public synchronized void addObserver(Observer o) Adds an observer to the set of observers of this object u public synchronized void deleteObserver(Observer o) Deletes an observer from the set of observers of this object u protected synchronized void setChanged() Indicates that this object has changed u protected synchronized void clearChanged() Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change. This method is called automatically by notifyObservers().

59 59 The java.util.Observable Class u public synchronized boolean hasChanged() Tests if this object has changed. Returns true if setChanged() has been called more recently than clearChanged() on this object; false otherwise. u public void notifyObservers(Object arg) If this object has changed, as indicated by the hasChanged() method, then notify all of its observers and then call the clearChanged() method to indicate that this object has no longer changed. Each observer has its update() method called with two arguments: this observable object and the arg argument. The arg argument can be used to indicate which attribute of the observable object has changed. u public void notifyObservers() Same as above, but the arg argument is set to null. That is, the observer is given no indication what attribute of the observable object has changed.

60 60 The java.util.Observer Interface u public abstract void update(Observable o, Object arg) This method is called whenever the observed object is changed. An application calls an observable object's notifyObservers method to have all the object's observers notified of the change. Parameters: o - the observable object arg - an argument passed to the notifyObservers method

61 61 Observable/Observer Example

62 62 ConcreteSubject.java import java.util.Observable; /** A subject to observe! */ public class ConcreteSubject extends Observable { private String name; private float price; public ConcreteSubject(String name, float price) { this.name = name; this.price = price; System.out.println("ConcreteSubject created: " + name + " at " + price); } public String getName() { return name; } public float getPrice() { return price; } public void setName(String name) { this.name = name; setChanged(); notifyObservers(name); } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(new Float(price)); }

63 63 Name and Price Observers import java.util.Observer; import java.util.Observable; // An observer of name changes. public class NameObserver implements Observer { private String name; public NameObserver() { name = null; System.out.println("NameObserver created: Name is " + name); } public void update(Observable obj, Object arg) { if (arg instanceof String) { name = (String)arg; System.out.println("NameObserver: Name changed to " + name); } import java.util.Observer; import java.util.Observable; // An observer of price changes. public class PriceObserver implements Observer { private float price; public PriceObserver() { price = 0; System.out.println("PriceObserver created: Price is " + price); } public void update(Observable obj, Object arg) { if (arg instanceof Float) { price = ((Float)arg).floatValue(); System.out.println("PriceObserver: Price changed to " + price); }

64 64 TestObservers.java import java.util.Observer; import java.util.Observable; // Test program for ConcreteSubject, NameObserver and PriceObserver public class TestObservers { public static void main(String args[]) { // Create the Subject and Observers. ConcreteSubject s = new ConcreteSubject("Corn Pops", 1.29f); NameObserver nameObs = new NameObserver(); PriceObserver priceObs = new PriceObserver(); // Add those Observers! s.addObserver(nameObs); s.addObserver(priceObs); // Make changes to the Subject. s.setName("Frosted Flakes"); s.setPrice(4.57f); s.setPrice(9.22f); s.setName("Surge Crispies"); }

65 65 A Simple MVC Example: CounterGui import java.awt.event.*; import java.awt.*; public class CounterGui extends Frame { private int counter = 0; // Model! private TextField tf = new TextField(10); // View. public CounterGui(String title) { super(title); Panel tfPanel = new Panel(); tf.setText("0"); tfPanel.add(tf); add("North", tfPanel); Panel buttonPanel = new Panel(); Button incButton = new Button("Increment"); incButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter++; tf.setText(counter + ""); } }); buttonPanel.add(incButton); Button decButton = new Button("Decrement"); decButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter--; tf.setText(counter + ""); } }); buttonPanel.add(decButton); Button exitButton = new Button("Exit"); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); buttonPanel.add(exitButton); add("South", buttonPanel); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] argv) { CounterGui cg = new CounterGui("CounterGui"); cg.setSize(300, 100); cg.setVisible(true); } Where is the controller in this example?? The controllers are the instances of the anonymous classes which handle the button presses.

66 66 Account System based on MVC Architecture from Advanced Java 2 Platform, How to Program, H. M. Deitel)

67 67 The Class Diagrams of the Account System

68 68 Sequence of Events :Controller :AccountTextView :Model 2.User updates accounts 1. Views subscribe to event 3. Request account change in model 4. Notify subscribers 5. Updated views :AccountBarGrapView :AssetPieChartView

69 69 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

70 70 Layout Managers u User interfaces made up of components u Components placed in containers u Container needs to arrange components u Swing doesn't use hard-coded pixel coordinates u Advantages: Can switch "look and feel" Can internationalize strings u Layout manager controls arrangement

71 71 Using Predefined Layout Managers There are several built-in layout managers in Java:  FlowLayout: left to right, start new row when full  BoxLayout: left to right or top to bottom  BorderLayout: 5 areas, Center, North, South, East, West  GridLayout: grid, all components have same size  GridBagLayout: complex, like HTML table

72 72 Layout Managers

73 73 Layout Managers u Set layout manager JPanel keyPanel = new JPanel(); keyPanel.setLayout(new GridLayout(4, 3)); u Add components for (int i = 0; i < 12; i++) keyPanel.add(button[i]);

74 74 Voice Mail System GUI u Same backend as text-based system u Only Telephone class changes u Buttons for keypad u Text areas for microphone, speaker

75 75 Voice Mail System GUI  Arrange keys in panel with GridLayout : JPanel keyPanel = new JPanel(); keyPanel.setLayout(new GridLayout(4, 3)); for (int i = 0; i < 12; i++) {JButton keyButton = new JButton(...); keyPanel.add(keyButton); keyButton.addActionListener(...); }

76 76 Voice Mail System GUI  Panel with BorderLayout for speaker JPanel speakerPanel = new JPanel(); speakerPanel.setLayout(new BorderLayout()); speakerPanel.add(new JLabel("Speaker:"), BorderLayout.NORTH); speakerField = new JTextArea(10, 25); speakerPanel.add(speakerField, BorderLayout.CENTER);

77 77 Voice Mail System GUI u Put speaker, keypads, and microphone panel into content pane u Content pane already has BorderLayout u Ch5/mailgui/Telephone.java

78 78 Telephone.java (1) import java.awt.*; import java.awt.event.*; import javax.swing.*; // Presents a phone GUI for the voice mail system. public class Telephone { // Constructs a telephone with a speaker, keypad, and microphone. public Telephone() { JPanel speakerPanel = new JPanel(); speakerPanel.setLayout(new BorderLayout()); speakerPanel.add(new JLabel("Speaker:"), BorderLayout.NORTH); speakerField = new JTextArea(10, 25); speakerPanel.add(speakerField, BorderLayout.CENTER); String keyLabels = "123456789*0#"; JPanel keyPanel = new JPanel(); keyPanel.setLayout(new GridLayout(4, 3)); for (int i = 0; i < keyLabels.length(); i++) { final String label = keyLabels.substring(i, i + 1); JButton keyButton = new JButton(label); keyPanel.add(keyButton); keyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { connect.dial(label); } }); } …..

79 79 Telephone.java (2) final JTextArea microphoneField = new JTextArea(10,25); JButton speechButton = new JButton("Send speech"); speechButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { connect.record(microphoneField.getText()); microphoneField.setText(""); } }); JButton hangupButton = new JButton("Hangup"); hangupButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { connect.hangup(); } }); …..

80 80 Telephone.java (3) JPanel buttonPanel = new JPanel(); buttonPanel.add(speechButton); buttonPanel.add(hangupButton); JPanel microphonePanel = new JPanel(); microphonePanel.setLayout(new BorderLayout()); microphonePanel.add(new JLabel("Microphone:"), BorderLayout.NORTH); microphonePanel.add(microphoneField, BorderLayout.CENTER); microphonePanel.add(buttonPanel, BorderLayout.SOUTH); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(speakerPanel, BorderLayout.NORTH); frame.add(keyPanel, BorderLayout.CENTER); frame.add(microphonePanel, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } // Give instructions to the mail system user. public void speak(String output) { speakerField.setText(output); } public void run(Connection c) { connect = c; } private JTextArea speakerField; private Connection connect; }

81 81 Implementing a Custom Layout Manager u It is not a difficult to write your own layout manager u Form layout u Odd-numbered components right aligned u Even-numbered components left aligned  Implement LayoutManager interface type

82 82 The LayoutManager Interface Type public interface LayoutManager { void layoutContainer(Container parent); Dimension minimumLayoutSize(Container parent); Dimension preferredLayoutSize(Container parent); void addLayoutComponent(String name, Component comp); void removeLayoutComponent(Component comp); } u Ch5/layout/FormLayout.java u Ch5/layout/FormLayoutTester.java  Note: Can use GridBagLayout to achieve the same effect

83 83 FormLayout.java (1) import java.awt.*; /** A layout manager that lays out components along a central axis */ public class FormLayout implements LayoutManager { public Dimension preferredLayoutSize(Container parent) { Component[] components = parent.getComponents(); left = 0; right = 0; height = 0; for (int i = 0; i < components.length; i += 2) { Component cleft = components[i]; Component cright = components[i + 1]; Dimension dleft = cleft.getPreferredSize(); Dimension dright = cright.getPreferredSize(); left = Math.max(left, dleft.width); right = Math.max(right, dright.width); height = height + Math.max(dleft.height, dright.height); } return new Dimension(left + GAP + right, height); } public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } …..

84 84 FormLayout.java (2) public void layoutContainer(Container parent) { preferredLayoutSize(parent); // Sets left, right Component[] components = parent.getComponents(); Insets insets = parent.getInsets(); int xcenter = insets.left + left; int y = insets.top; for (int i = 0; i < components.length; i += 2) { Component cleft = components[i]; Component cright = components[i + 1]; Dimension dleft = cleft.getPreferredSize(); Dimension dright = cright.getPreferredSize(); int height = Math.max(dleft.height, dright.height); cleft.setBounds(xcenter - dleft.width, y + (height - dleft.height) / 2, dleft.width, dleft.height); cright.setBounds(xcenter + GAP, y + (height - dright.height) / 2, dright.width, dright.height); y += height; } public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} private int left; private int right; private int height; private static final int GAP = 6; }

85 85 FormLayoutTester.java import java.awt.*; import javax.swing.*; public class FormLayoutTester { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(new FormLayout()); frame.add(new JLabel("Name")); frame.add(new JTextField(15)); frame.add(new JLabel("Address")); frame.add(new JTextField(20)); frame.add(new JLabel("City")); frame.add(new JTextField(10)); frame.add(new JLabel("State")); frame.add(new JTextField(2)); frame.add(new JLabel("ZIP")); frame.add(new JTextField(5)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }

86 86 Strategy Pattern u Pluggable strategy for layout management u Layout manager object responsible for executing concrete strategy u Generalizes to Strategy Design Pattern u The strategy pattern applies whenever you want to allow a client to support an algorithm. u It is a behavioral pattern for selecting one of many algorithms

87 87 Strategy Pattern Solution 1.Define an interface type that is an abstraction for the algorithm 2.Actual strategy classes realize this interface type. 3.Clients can supply strategy objects 4.Whenever the algorithm needs to be executed, the context class calls the appropriate methods of the strategy object Context 1.A class can benefit from different variants for an algorithm 2.Clients sometimes want to replace standard algorithms with custom versions

88 88 Strategy Pattern Example: Layout Management Name in Design PatternActual Name (layout management) ContextContainer StrategyLayoutManager ConcreteStrategya layout manager such as BorderLayout doWork()a method such as layoutContainer u The relationships between the names in the Strategy Pattern and the layout management manifestation:

89 89 Strategy Pattern Example: Sorting Name in Design PatternActual Name (sorting) ContextCollections StrategyComparator ConcreteStrategya class that implements Comparator u Other manifestation: Comparators Comparator comp = new CountryComparatorByName(); Collections.sort(countries, comp);

90 90 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

91 91 Containers and Components u Containers collect GUI components u Sometimes, want to add a container to another container u Container should be a component u Composite design pattern u Composite method typically invoke component methods  E.g. Container.getPreferredSize invokes getPreferredSize of components u It is a structural pattern for building recursive aggregations

92 92 Composite Pattern Context 1.Primitive objects can be combined to composite objects 2.Clients treat a composite object as a primitive object Solution 1.Define an interface type that is an abstraction for the primitive objects 2.Composite object collects primitive objects 3.Composite and primitive classes implement same interface type. 4.When implementing a method from the interface type, the composite class applies the method to its primitive objects and combines the results

93 93 Composite Pattern Example in Java Name in Design PatternActual Name (AWT components) PrimitiveComponent CompositeContainer Leafa component without children (e.g. JButton) method()a method of Component (e.g.getPreferredSize)

94 94 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

95 95 Scroll Bars u Scroll bars can be attached to components  Approach #1: Component class can turn on scroll bars u Approach #2: Scroll bars can surround component JScrollPane pane = new JScrollPane(component); u Swing uses approach #2  JScrollPane is again a component u It is a structural pattern for extending an object transparently

96 96 Decorator Pattern - Context Context 1.Component objects can be decorated (visually or behaviorally enhanced) 2.The decorated object can be used in the same way as the undecorated object 3.The component class does not want to take on the responsibility of the decoration 4.There may be an open-ended set of possible decorations

97 97 Decorator Pattern - Solution Solution 1.Define an interface type that is an abstraction for the component 2.Concrete component classes realize this interface type. 3.Decorator classes also realize this interface type. 4.A decorator object manages the component object that it decorates 5.When implementing a method from the component interface type, the decorator class applies the method to the decorated component and combines the result with the effect of the decoration.

98 98 Decorator Pattern Example: Scroll Bars Name in Design PatternActual Name (scroll bars) Component ConcreteComponentJTextArea DecoratorJScrollPane method()a method of Component (e.g. paint)

99 99 Decorator Pattern Example: Streams InputStreamReader reader = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(reader);  BufferedReader takes a Reader and adds buffering  Result is another Reader : Decorator pattern  Many other decorators in stream library, e.g. PrintWriter Name in Design PatternActual Name (input streams) ComponentReader ConcreteComponentInputStreamReader DecoratorBufferedReader method()read

100 100 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

101 101 How to Recognize Patterns u Look at the intent of the pattern u E.g. COMPOSITE has different intent than DECORATOR u Remember common uses (e.g. STRATEGY for layout managers) u Not everything that is strategic is an example of STRATEGY pattern u Use context and solution as "litmus test"

102 102 Litmus Test u Add border to Swing component Border b = new EtchedBorder(); component.setBorder(b); u Undeniably decorative u Is it an example of DECORATOR?

103 103 Litmus Test 1.Component objects can be decorated (visually or behaviorally enhanced) PASS 2.The decorated object can be used in the same way as the undecorated object PASS 3.The component class does not want to take on the responsibility of the decoration FAIL--the component class has setBorder method 4.There may be an open-ended set of possible decorations

104 104 1.The ITERATOR as a Pattern 2.The Pattern Concept and Introduction to GoF Design Patterns 3.The OBSERVER Pattern 4.Layout Managers and the STRATEGY Pattern 5.Components, Containers, and the COMPOSITE Pattern 6.Scroll Bars and the DECORATOR Pattern 7.How to Recognize Patterns 8.Putting Patterns to Work

105 105 Putting Patterns to Work u Invoice contains line items u Line item has description, price  Interface type LineItem : u Ch5/invoice/LineItem.java u Product is a concrete class that implements this interface: u Ch5/invoice/Product.java

106 106 LineItem.java and Product.java /** A line item in an invoice. */ public interface LineItem { /** Gets the price of this line item. @return the price */ double getPrice(); /** Gets the description of this line item. @return the description */ String toString(); } /** A product with a price and description. */ public class Product implements LineItem { /** Constructs a product. @param description the description @param price the price */ public Product(String description, double price) { this.description = description; this.price = price; } public double getPrice() { return price; } public String toString() { return description; } private String description; private double price; }

107 107 Bundles u Bundle = set of related items with description+price u E.g. stereo system with tuner, amplifier, CD player + speakers u A bundle has line items u A bundle is a line item u COMPOSITE pattern  Ch5/invoice/Bundle.java (look at getPrice )

108 108 Bundle.java import java.util.*; // A bundle of line items that is again a line item. public class Bundle implements LineItem { // Constructs a bundle with no items. public Bundle() { items = new ArrayList (); } /** Adds an item to the bundle. @param item the item to add */ public void add(LineItem item) { items.add(item); } public double getPrice() { double price = 0; for (LineItem item : items) price += item.getPrice(); return price; } public String toString() { String description = "Bundle: "; for (int i = 0; i < items.size(); i++) { if (i > 0) description += ", "; description += items.get(i).toString(); } return description; } private ArrayList items; }

109 109 Discounted Items u Store may give discount for an item u Discounted item is again an item u DECORATOR pattern  Ch5/invoice/DiscountedItem.java (look at getPrice )  Alternative design: add discount to LineItem

110 110 DiscountedItem.java /** A decorator for an item that applies a discount. */ public class DiscountedItem implements LineItem { /** Constructs a discounted item. @param item the item to be discounted @param discount the discount percentage */ public DiscountedItem(LineItem item, double discount) { this.item = item; this.discount = discount; } public double getPrice() { return item.getPrice() * (1 - discount / 100); } public String toString() { return item.toString() + " (Discount " + discount + "%)"; } private LineItem item; private double discount; }

111 111 Model/View Separation u GUI has commands to add items to invoice u GUI displays invoice u Decouple input from display u Display wants to know when invoice is modified u Display doesn't care which command modified invoice u OBSERVER pattern

112 112 Change Listeners  Use standard ChangeListener interface type public interface ChangeListener { void stateChanged(ChangeEvent event); }  Invoice collects ArrayList of change listeners u When the invoice changes, it notifies all listeners: ChangeEvent event = new ChangeEvent(this); for (ChangeListener listener : listeners) listener.stateChanged(event);

113 113 Change Listeners u Display adds itself as a change listener to the invoice u Display updates itself when invoice object changes state final Invoice invoice = new Invoice(); final JTextArea textArea = new JTextArea(20, 40); ChangeListener listener = new ChangeListener() { public void stateChanged(ChangeEvent event) { textArea.setText(...); } };

114 114 Observing the Invoice

115 115 Iterating Through Invoice Items u Invoice collect line items u Clients need to iterate over line items  Don't want to expose ArrayList u May change (e.g. if storing invoices in database) u ITERATOR pattern

116 116 Iterators u Use standard Iterator interface type public interface Iterator {boolean hasNext(); LineItem next(); void remove(); }  remove is "optional operation" (see ch. 8)  implement to throw UnsupportedException  implement hasNext/next manually to show inner workings u Ch5/invoice/Invoice.java

117 117 Invoice.java (1) import java.util.*; import javax.swing.event.*; // An invoice for a sale, consisting of line items. public class Invoice { // Constructs a blank invoice. public Invoice() { items = new ArrayList (); listeners = new ArrayList (); } /** Adds an item to the invoice. @param item the item to add */ public void addItem(LineItem item) { items.add(item); // Notify all observers of the change to the invoice ChangeEvent event = new ChangeEvent(this); for (ChangeListener listener : listeners) listener.stateChanged(event); } /** Adds a change listener to the invoice. @param listener the change listener to add */ public void addChangeListener(ChangeListener listener) { listeners.add(listener); } ….

118 118 Invoice.java (2) /** Gets an iterator that iterates through the items. @return an iterator for the items */ public Iterator getItems() { return new Iterator () { public boolean hasNext() { return current < items.size(); } public LineItem next() { return items.get(current++); } public void remove() { throw new UnsupportedOperationException(); } private int current = 0; }; } public String format(InvoiceFormatter formatter) { String r = formatter.formatHeader(); Iterator iter = getItems(); while (iter.hasNext()) r += formatter.formatLineItem(iter.next()); return r + formatter.formatFooter(); } private ArrayList items; private ArrayList listeners; }

119 119 Formatting Invoices u Simple format: dump into text area u May not be good enough, u E.g. HTML tags for display in browser u Want to allow for multiple formatting algorithms u STRATEGY pattern

120 120 InvoiceFormatter.java /** This interface describes the tasks that an invoice formatter needs to carry out. */ public interface InvoiceFormatter { /** Formats the header of the invoice. @return the invoice header */ String formatHeader(); /** Formats a line item of the invoice. @return the formatted line item */ String formatLineItem(LineItem item); /** Formats the footer of the invoice. @return the invoice footer */ String formatFooter(); }

121 121 SimpleFormatter.java /** A simple invoice formatter. */ public class SimpleFormatter implements InvoiceFormatter { public String formatHeader() { total = 0; return " I N V O I C E\n\n\n"; } public String formatLineItem(LineItem item) { total += item.getPrice(); return (String.format( "%s: $%.2f\n",item.toString(),item.getPrice())); } public String formatFooter() { return (String.format("\n\nTOTAL DUE: $%.2f\n", total)); } private double total; }

122 122 InvoiceTester.java (1) import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; // A program that tests the invoice classes. public class InvoiceTester { public static void main(String[] args) { final Invoice invoice = new Invoice(); final InvoiceFormatter formatter = new SimpleFormatter(); // This text area will contain the formatted invoice final JTextArea textArea = new JTextArea(20, 40); // When the invoice changes, update the text area ChangeListener listener = new ChangeListener() { public void stateChanged(ChangeEvent event) { textArea.setText(invoice.format(formatter)); } }; invoice.addChangeListener(listener); // Add line items to a combo box final JComboBox combo = new JComboBox(); Product hammer = new Product("Hammer", 19.95); Product nails = new Product("Assorted nails", 9.95); combo.addItem(hammer); Bundle bundle = new Bundle(); bundle.add(hammer); bundle.add(nails); combo.addItem(new DiscountedItem(bundle, 10)); …

123 123 InvoiceTester.java // Make a button for adding the currently selected // item to the invoice JButton addButton = new JButton("Add"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { LineItem item = (LineItem) combo.getSelectedItem(); invoice.addItem(item); } }); // Put the combo box and the add button into a panel JPanel panel = new JPanel(); panel.add(combo); panel.add(addButton); // Add the text area and panel to the content pane JFrame frame = new JFrame(); frame.add(new JScrollPane(textArea), BorderLayout.CENTER); frame.add(panel, BorderLayout.SOUTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }

124 124 Formatting Invoices

125 125 Formatting Invoices

126 126 References This lecture is mainly based on the book Object Oriented Design and Patterns [1]. There are also some slides adapted from various resources and my own slides. They are cited below: Main Resources: 1.C. Horstmann, Object Oriented Design and Patterns (OODP), 2nd Edition,, John Wiley, ISBN: 0-471-74487-5, 2005. 2.E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1995. 3.Lecture notes of CENG 535/410 Design Patterns course at Fatih University: http://www.fatih.edu.tr/~haluk/Teaching/Fatih/2003%20Fall/ceng%20534/ce ng534-2003.htm http://www.fatih.edu.tr/~haluk/Teaching/Fatih/2003%20Fall/ceng%20534/ce ng534-2003.htm


Download ppt "1 CENG 217 Object Oriented Design Lecture 5 Doç. Dr. Halûk Gümüşkaya / Computing Engineering."

Similar presentations


Ads by Google