1 CSE 331 The Strategy and State Patterns slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia

Slides:



Advertisements
Similar presentations
1 CSE 331 Enumerated types ( enum ) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Advertisements

Chapter 1: Computer Systems
The Last Procedure Before First Functional Prototype Grant Boomer, Brett Papineau, Tanis Lopez, Archana Shrestha CS 383.
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
SE2811 Week 7, Class 2 The Gang of Four and more … Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder.
Object Oriented Programming Lecture 7: Algorithm animation using strategy and factory patterns, The Adapter design pattern
1 Patterns & GUI Programming Part 2. 2 Creating a Custom Layout Manager Layout manager determines how components are arranged/displayed in a container.
13-Jun-15 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
CSE 143 Lecture 7 Stacks and Queues reading: Stuart Reges notes on website slides created by Marty Stepp
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4 Objects and Classes.
Design Patterns and Graphical User Interfaces Horstmann ,
Design Dan Fleck CS 421 George Mason University. What is the design phase? Analysis phase describes what the system should do Analysis has provided a.
MA/CSSE 473 Day 31 Student questions Data Compression Minimal Spanning Tree Intro.
1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Factory, Command.
CS 325: Software Engineering March 17, 2015 Applying Patterns (Part A) The Façade Pattern The Adapter Pattern Interfaces & Implementations The Strategy.
1 CSE 331 Introduction; Review of Java and OOP slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
Othello Artificial Intelligence With Machine Learning
Computer Science 209 The Strategy Pattern I: Comparisons and Layouts.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
Chapter 26 GoF Design Patterns. The Adapter Design Pattern.
The Java Programming Language
1 CSE 403 Design Patterns and GUI Programming Reading: Object-Oriented Design and Patterns, Ch. 5 (Horstmann) These lecture slides are copyright (C) Marty.
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
3-1 State Design Pattern C Sc 335 Rick Mercer. State Design Pattern State is one of the Behavioral patterns It is similar to Strategy Allows an object.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
Design Patterns Based on The Design Patterns Java Companion by James Cooper
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Mediator Kensho Tsuchihashi. Mediator Page 2 Table of Contents 1.What is Mediator? 2.What problem does Mediator solve? 3.Advantage and Disadvantage 4.Additional.
Design Patterns Yonglei Tao. Design Patterns  A design pattern describes a recurring design problem, a solution, and the context in which that solution.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Object-Oriented Design Patterns CSC 335: Object-Oriented Programming and Design.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
CSE 403 Lecture 9 UML State Diagrams Reading:
Design Patterns Introduction
6-Jan-16 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
1 CSE 331 Design Patterns 1: Iterator, Adapter, Singleton, Flyweight slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin,
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Abstract Data Types and Stacks CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
More Patterns CS 124. More Basic Patterns Patterns you’ve already seen (without knowing it) Observer / Listener Wrapper Composite Decorator / Filter Patterns.
Session 30 Final Review. Final Details Wednesday, December 14 at 8 AM Wright 5 (same classroom) Final will be comprehensive Open book Open notes Test.
L10: Model-View-Controller General application structure. User Interface: Role, Requirements, Problems Design patterns: Model – View – Controller, Observer/Observable.
1 CSE 331 Composite Layouts; Decorators slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Recursion Chapter What is recursion? Recursion occurs when a method calls itself, either directly or indirectly. Used to solve difficult, repetitive.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Chapter 5 Patterns and GUI Programming -Part 1-. Pattern A pattern is a description of a problem and its solution that you can apply to many programming.
Chapter 5 Patterns and GUI Programming -Part 2-. STRATEGY Pattern Layout Managers What if we need to specifies pixel position of components when  User.
Building Java Programs
Design Patterns Lecture part 2.
CSE 403 Lecture 9 UML State Diagrams Reading:
Data Structures ADT List
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Software Design Lecture : 39.
Binary Search Trees Based on slides by Marty Stepp & Alyssa Harding
Software Specifications
Presentation transcript:

1 CSE 331 The Strategy and State Patterns slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia

2 Gang of Four (GoF) patterns Creational Patterns (abstracting the object-instantiation process)  Factory MethodAbstract FactorySingleton  BuilderPrototype Structural Patterns (how objects/classes can be combined)  AdapterBridgeComposite  DecoratorFacadeFlyweight  Proxy Behavioral Patterns (communication between objects)  CommandInterpreterIterator  MediatorObserverState  StrategyChain of ResponsibilityVisitor  Template Method

3 Pattern: Strategy objects that hold different algorithms to solve a problem

4 The problem situation Problem: We want to generalize behavior of one part of our app.  Example: Layout of components within containers.  Example: Ways of sorting to arrange data.  Example: Computer game player AI algorithms. Poor solutions to the problem:  Boolean flags or many set methods to enable various algorithms. myContainer.useFlow(); game.playerDifficulty(3);  Lots of if statements in our app to choose between algorithms. if (abc) { mergeSort(data); } else if (xyz) { bubbleSort(data); }  Rewriting entire model classes just to change the algorithm. FlowContainer, BorderContainer,..., EasyPlayer, HardPlayer

5 strategy: An algorithm separated from the object that uses it, and encapsulated as its own object.  A behavioral pattern.  Each strategy implements one specific behavior; one implementation of how to solve the same problem.  Separates algorithm for behavior from object that wants to act.  Allows changing an object's behavior dynamically without extending or changing the object itself. examples:  file saving; file compression; sorting; Comparator s  layout managers on GUI containers  AI algorithms for computer game players Strategy pattern

6 Implementing strategies Write an interface representing the general behavior / algorithm. public interface CardStrategy {...} Provide a way to supply an object that meets this interface into the larger overall model (sometimes called dependency injection ). public class CardGame { public void setStrategy(CardStrategy strat) {...} } Write classes that implement the interface w/ specific algorithms. public class TimidStrategy implements CardStrategy {...} public class RandomStrategy implements CardStrategy {...} public class CleverStrategy implements CardStrategy {...}

7 LayoutManager strategies Layout managers in Java implement the Strategy pattern.  Each LayoutManager object has an algorithm to position components. public interface LayoutManager { void addLayoutComponent(String name, Component comp); void layoutContainer(Container container); Dimension minimumLayoutSize(Container parent); Dimension preferredLayoutSize(Container parent); void removeLayoutComponent(Component comp); } public class BorderLayout implements LayoutManager {...} public class FlowLayout implements LayoutManager {...} public class GridLayout implements LayoutManager {...}

8 Custom layout example import java.awt.*; // Lays out components at preferred sizes in a stack that // cascades from top/left down with 20px between each. public class CascadingLayout implements LayoutManager { private static final int GAP = 20; public void layoutContainer(Container container) { int xy = 0; for (Component comp : container.getComponents()) { comp.setSize(comp.getPreferredSize()); comp.setLocation(xy, xy); xy += GAP; } public Dimension minimumLayoutSize(Container c) { return new Dimension(0, 0); } public Dimension preferredLayoutSize(Container c) { return new Dimension(500, 500); } public void addLayoutComponent(String n, Component c) {} public void removeLayoutComponent(Component c) {} }

9 Strategies as observers Sometimes strategies must react to changes in the state of a model.  Example: Game player strategies must play when it is their turn. So it can be useful to have the strategy observe the model:  myGame.addObserver(myStrategy); Possible complication: Can the strategy do something malicious? Can a rogue strategy put the game into an invalid state?  How might we avoid or fix this problem?

10 Strategy exercise Modify the Rock-Paper-Scissors game to pit a human player against a computer player. Give the computer player the ability to use different strategies:  RockStrategy : Always chooses rock.  RandomStrategy : Chooses completely at random.  LearningStrategy : Chooses the weapon to beat the weapon that was chosen by the human player last game.  StatisticalStrategy : Chooses the weapon that will beat the weapon being used by the human player the majority if the time. If there is a tie, chooses any weapon randomly.

11 Pattern: State representing the state of one object using another object

12 The problem situation Problem: We have a model with complex states.  Example: A poker game that can be in progress, betting, drawing,...  Example: A network app that can wait for messages, send,...  Various parts of our code (in and out of the model) need to understand and react to that state in different ways. Poor solutions to the problem:  Trying to deduce the model's state based on complex analysis of various fields within the model. if the winner is null and current player is p2, then... if my message buffer queue is empty and 0 bytes available, then...

13 state: An object whose sole purpose is to represent the current "state" or configuration of another larger object.  A behavioral pattern.  Often implemented with an enum type for the states.  Each state object represents one specific state for the larger object.  The larger object will set its state in response to various mutations.  Allows various observers and interested parties to quickly and accurately know what is going on with the larger object's status. Analogous to the notion of finite state machines.  Set of states (nodes)  Set of edges (mutations that cause state changes) State pattern

14 State enum example // Represents states for a poker game. public enum GameState { NOT_STARTED, IN_PROGRESS, WAITING_FOR_BETS, DEALING, GAME_OVER; } // Poker game model class. public class PokerGame { private GameState state; public GameState getState() { return state; } public void ante(int amount) {... state = WAITING_FOR_BETS; // change state setChanged(); notifyObservers(state); }