9
Design Patterns Introduction to Patterns 1. A design pattern is the outline of a reusable solution to a general problem encountered in a particular context. A design pattern is not code, it is a description or template for how to solve a general problem. A design pattern is a best practice for approaching a specific type of problem. Strategy Pattern 1. Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. By associating the client with a strategy/algorithm we allow different objects to use different algorithms and to swap algorithms at run-time. Strategy in Java 1. The TreeSet constructor can take a Comparator. TreeMap, and Collections.sort are similar. 2. In Java Swing, the JComponent class utilizes strategy with the Border interface while the Container class utilizes strategy with the LayoutManager interface. JComponent utilizes the strategy pattern in a number of other places including: ActionMap (locates Actions when a key is pressed) and 1

CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

Design Patterns

Introduction to Patterns

1. A design pattern is the outline of a reusable solution to a general problem encountered in a particular context. A design pattern is not code, it is a description or template for how to solve a general problem. A design pattern is a best practice for approaching a specific type of problem.

Strategy Pattern

1. Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable.

By associating the client with a strategy/algorithm we allow different objects to use different algorithms and to swap algorithms at run-time.

Strategy in Java

1. The TreeSet constructor can take a Comparator.

TreeMap, and Collections.sort are similar.

2. In Java Swing, the JComponent class utilizes strategy with the Border interface while the Container class utilizes strategy with the LayoutManager interface. JComponent utilizes the strategy pattern in a number of other places including: ActionMap (locates Actions when a key is pressed) and JPopupMenu. In JavaFX, the strategy pattern is similarly found in the relationship between a Stage and a Scene and a Scene and a Pane (more generally, a Pane).

1

Page 2: CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

Other Examples

1. Chess – Pawn, Bishop, Rook, etc move differently.2. Overtime pay – Different types of workers (Hourly, Salaried, Manager, etc) are paid overtime differently.3. Online shopping – A shopping website suggests products in a sidebar, perhaps depending on the type of user:

anonymous or registered. Suggestions could be: random, best sellers, clearance, sales items, new products, etc.4. Online shopping – tax calculations for purchase orders depend on the state the purchaser is in.5. Online shopping – Different types of coupons have different discounts.6. File formats – read (or write) files in different formats.7. A date class that can format dates in numerous ways, including a custom format.8. A graph can be drawn as bar graph, line graph, pie chart, etc.9. A component to generate SQL statements for different databases (Oracle, SQL Server, MySQL)10. Compress files with different algorithms.11. Drawing graphics with different algorithms (anti-alias, direct, others)12. Forecasting demand (or anything) using different techniques.13. Line-breaking algorithms.

2

Page 3: CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

Observer Pattern

1. A common situation is when you have some object (Context) and when it’s state changes, it needs to call methods in other objects (DependentObj’s):

What are the problems with this?

1. Requires the context to have concrete references to the dependent objects. What if dependent objects change? What if we want to add another dependent object? We will have to change the context too.

2. What if the dependent objects are only known at run time? There may be other classes that supply the services.

3. What if we want to swap out dependent objects at run-time. We can’t do it unless they have the same class.

4. It is easy to get the dependent objects responsibility (or part of it) embedded in the context.

All this points to heavy coupling which we would like to avoid.

2. The figure below is the solution to the problem above and is called the Observer Pattern. The idea is that Observers observe objects that are Observable. When an Observable object changes, it calls notify to inform all the Observers. In the figure, we’ve left open the question of what data to pass in update. The advantage to this is that Observables don’t need to know anything about the concrete classes of Observers. They just know that they have an update method.

The Observer Pattern provides a mechanism so that an object can notify dependent objects of changes without having to know their concrete classes.

The Observer Pattern defines a one-to-many dependency between object so that when one object changes state, all of its dependents are notified and updated automatically [HFDP]

3

Page 4: CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

3. Example. The Observer pattern transforms:

to:

Observer in Java

1. The java.util package supplies the (concrete) Observable class and the Observer interface as shown below.

Implementation details:

a. The Observable class has a private flag that is set to false initially. When the flag is false, a call to notify does nothing, the observers are not notified. However, Java provides a protected method, setChanged which sets the flag to true. Then, a subsequent call to notify will call update on all observers and then sets the flag back to false. So, we can view this flag as a protection mechanism in the sense that clients can call notify at any time, but notify will only work when the subclass case previously called setChanged. Thus, a client can call notify, but only the concrete observable can allow the notification to take place.

b. The update method has two parameters, a reference to the observable and an arbitrary Object.

c. The notify method is overloaded. If it is called with no argument, then null is used as an argument in the update method. Otherwise, notify can be called with an argument which is then used as an argument to the update method. Thus, we can push information to the observers if we want.

d. The order of notification of observers is not specified. In other words, if we want a specific order, we would need to write our own Observable.

4

Page 5: CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

2. GUI Event handling in Java utilizes the Observer Pattern. GUI elements that can be interacted with by a user. For instance, when a user presses a button, an event is fired, which triggers the execution of some code to handle the event. In Java, ActionListeners handle events by supplying an actionPerformed method and are registered with GUI elements.

Homework

1. Code this example of the Observer pattern using Java’s Observable class and Observer interface.

2. Consider a system where a voting component receives votes for a set of candidates that are running for an office. Clients can use the component to cast a single vote for a single candidate. In other words, voting is one-at-a-time. Other periodically receive updates on the voting and display the data either with a table, bar graph, pie chart, or some other form(s) to be developed later. The voting component notifies the display clients every time 10 new votes have been received.

5

Page 6: CS 1301 – Ch 6, Handout 1 - Valdosta State University · Web viewDesign Patterns Introduction to Patterns A design pattern is the outline of a reusable solution to a general problem

a. Model this system using UML and design pattern(s) as completely as possible. Use notes as necessary to annotate the drawing.

b. State and indicate any patterns you are using. Hint: both Observer and Strategy are useful here.

Solutions

1. Solution not available at present, email me if you want it and I’ll do it.

2. .

6