Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS202 Lecture 16.

Similar presentations


Presentation on theme: "CS202 Lecture 16."— Presentation transcript:

1 CS202 Lecture 16

2 Design Patterns The second mouse gets the cheese.

3 Design Patterns You have noticed by now that there are many archetypal problems that arise over and over in programming need to do the same kind of task using different algorithms in different situations provide a new interface for an existing class so it can be used in a new context access the objects in a collection one by one without giving client code access to implementation details pool a group of objects so they can be reused by client code without the expense of instantiating new ones switch among a set of discrete states (eg, a traffic light)

4 Design Patterns Definition from Wikipedia:
A software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.  Patterns don’t consist of code or pseudocode, but of high-level descriptions of the solution and of the relationships between entities used in the pattern (classes and interfaces) When you recognize a situation as one where a particular pattern would provide a good solution, you are only at the end of the beginning of creating the solution.

5 Design Patterns Patterns help you recognize typical design issues when they arise Patterns help you see solutions that other developers have already worked out Patterns help to standardize programming practices, which makes it easier to understand, debug, or extend other programmers' code

6 Design Patterns The patterns I describe in this lecture are chosen because they are easy to understand and/or because I am going to use them in an upcoming example of a JavaFX table. There are dozens of other widely-recognized patterns. You will probably learn additional patterns in various advanced programming classes, but I recommend that you read a book on this topic to get a general familiarity with a variety of patterns. Head First Design Patterns, which uses Java for its examples, is one good alternative. The Bible of patterns is Design Patterns: Elements of Reusable Object-Oriented Software by  Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, also known as the "Gang Of Four book." This book, however, is not especially easy to understand. There is a good but very incomplete list of common patterns at

7 Strategy Pattern The Strategy pattern provides interchangeable algorithms for solving some problem by encapsulating them in objects. In Java, Strategy is implemented using a Java interface with multiple implementations. Each implementing class can use a different algorithm. A Strategy pattern can be set up so that the particular algorithm can be chosen at runtime based on characteristics of the actual data or other considerations. Arrays.sort() implements the Strategy pattern; it chooses the particular type of sort to use, and this is transparent to client code. An application that can save files in different file formats might use Strategy, deciding at runtime which implementation to use Several of my labs have been designed to give you a sense of the type of situation in which you would use Strategy

8 Strategy Pattern

9 Strategy Pattern Source:

10 Strategy Pattern When a pattern has conventional terms for the classes and interfaces, use them in your code. Other developers will understand much of how your code works as soon as they see that you are using the pattern. For example, in Strategy, use the word Strategy in the name of the interface, eg PaymentStrategy, and in the names of the implementations, eg CreditCardStrategy.

11 Template Method Somewhat similar to Strategy, but implemented using inheritance rather than interface implementations Definition from Wikipedia: the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses.  Skeleton of an algorithm is coded in an abstract class, calling additional methods at various steps. Some of the additional methods may work the same way for all variants of the algorithm and may be coded in the abstract class. Different concrete subclasses implement other methods differently.

12 Template Method

13 Template Method Calls readData() And processData()

14 Template Method Vs. Strategy
Java programmers typically prefer the more abstract approach of using interfaces, as in the Strategy pattern, over using inheritance, as in Template Method, because inheritance is more complex. Template Method code is hard to follow because it interleaves individual lines of code in the abstract class with calls to methods that are defined in the subclasses. The flip side of this is that the Template Method pattern reduces the amount of code necessary if the different variations of an algorithm have comparatively small differences. Because TM eliminates duplication, it is much easier to change the code if some fundamental aspect of the algorithm or interface has to change.

15 Observer Pattern The observer pattern is a pattern in which an object, called the subject, maintains a list of clients, called observers, and notifies them automatically of any state changes, usually by making method calls on the observers. The subject is also called an observable object. Used in many GUI toolkits to implement event handling, especially with the Model-View-Controller pattern Adapted from Wikipedia

16 Observer Pattern Wikipedia

17 State Pattern Set up an object that changes state among a discrete set of possibilities The States might be subclasses of a parent class, might implement an interface, or might just be variable values (for example, the different values of an enum) Avoid the need for hard-to-understand conditional blocks

18 State Pattern

19 State Pattern package traffic;
// adapted from public abstract class TrafficSignal { public final static int GO = 0; public final static int CAUTION = 1; public final static int STOP = 2; public final static int NUMBER_OF_STATES = 3; boolean passageRequested = false; int state = STOP; public boolean getPassageRequested() { return passageRequested; } public void requestPassage() { if (state == STOP) { passageRequested = true; public void changeState() { this.state = (state + 1) % NUMBER_OF_STATES; if (state == GO) { passageRequested = false; public int getState() { return state; public abstract String getMessage();

20 State Pattern package traffic;
public class TrafficLight extends TrafficSignal { public String getMessage() { switch (state) { case STOP: return "red"; case GO: return "green"; case CAUTION: return "yellow"; default: return "illegal state"; }

21 State Pattern package traffic;
public class WalkSign extends TrafficSignal { public String getMessage() { switch (state) { case STOP: return "Don't Walk"; case GO: return "Walk"; case CAUTION: return "Flashing Don't Walk"; default: return "illegal state"; }

22 State Pattern package traffic; import static org.junit.Assert.*;
import org.junit.Test; public class TrafficTest { @Test public void testTrafficLightCreated() { TrafficSignal t = new TrafficLight(); assertNotNull(t); } public void testWalkSignCreated() { TrafficSignal w = new WalkSign(); assertNotNull(w); public void testTrafficLightInitialState() { String stopMessage = "red"; assertEquals(t.getMessage(), stopMessage); public void testChangeTrafficLightState() { t.changeState(); String goMessage = "green"; assertEquals(t.getMessage(), goMessage); public void testTrafficLightFullCycle() { String initState = t.getMessage(); for (int counter = 0; counter < 3; counter++) assertEquals(t.getMessage(), initState); // not complete; also need to fully test WalkSignal

23 State Transition Here is a different traffic light state example which I can’t call an example of a “design pattern” since it is from non-OOP code. However, it is easy to relate to. This one has three input sensors: sensor 0, place value = 0: car waiting on westbound street sensor 1, place value = 2: car waiting on southbound street sensor 2, place value = 4: pedestrian waiting anywhere. There are 23 = 8 possible inputs, namely 0 (no waiting anywhere) through 7 (all sensors show waiting.) : Outputs are #defined in C as seven states: #define WGO // west go, all else stop #define WWT // west caution, all else stop #define SGO // south go, all else stop #define SWT // south caution, all else stop #define PGO // pedestrian go, all else stop #define PWTa // pedestrian caution blink off, all else stop #define PWTb 6 // pedestrian caution blink on, all else stop Here are the state transitions, extracted from C structs. In Java they would probably be defined in arrays. Each array shows the next state for a given input (0-7): {0,0,1,1,1,1,1,1} {0,0,2,2,4,4,2,4} {2,3,2,3,3,3,3,3} {0,0,2,0,4,4,4,0} {5,5,5,5,4,5,5,5} {6,6,6,6,6,6,6,6} {0,0,2,0,4,0,2,2}

24 Adapter Pattern The Adapter pattern connects a class to client code that requires a different interface. Adapter is useful when a class or module already provides the functionality you need, but you can’t change it to provide the correct interface Example: an existing class works with a database to create csv documents and makes them available though a getter, but your other code needs to get .xls documents. Solution: write an adapter that implements the interface you need, and that calls the getter in the existing class and then converts the csv to xls. Adapter is particularly useful when two existing applications need to communicate; suppose the registrar and the financial aid office use systems with different Student classes, but each needs to get information from the other. Adapter is also commonly used to help applications use libraries. Suppose you find another graph library that you like better than JFreeChart, but want to minimize changes to your existing lab 6 code. Write a set of adapters with the interfaces you are already using, and which then use the new library in the background.

25 Adapter Pattern Source: This shows Adapter as an interface. If there will be many types of adapters that are only slightly different from each other, Adapter could be an abstract class instead.


Download ppt "CS202 Lecture 16."

Similar presentations


Ads by Google