Zahra Moslehi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design pattern Course Fall 2010.

Slides:



Advertisements
Similar presentations
1 Todays Objectives Announcements Homework #1 is due next week Return Quiz 1 – answers are posted on the Yahoo discussion page site Basic Java Programming.
Advertisements

GoF State Pattern Aaron Jacobs State(305) Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
The Singleton Pattern II Recursive Linked Structures.
Notes from HW3 / Lab3 Program documentation – At the top of every class: //************************************************************ // seu01.java Author:
Written by: Dr. JJ Shepherd
T O K ILL A S INGLETON F ACTORY M ETHOD P ATTERN Josh Mason 6/18/09.
INTRANET MAIL SERVER (DESIGN OF SMTP and POP3)
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Matt Klein 7/6/2009.  Behavioral Pattern  Intent  Allow an object to alter its behavior when its internal state changes. The object will appear to.
JBoss Seam: Contextual Components Jason Bechtel
Reza Gorgan Mohammadi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design.
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
Design Patterns I 1. Creational Pattern Singleton: intent and structure Ensure a class has one instance, and provide a global point of access to it 2.
CPSC 441: FTP & SMTP1 Application Layer: FTP & Instructor: Carey Williamson Office: ICT Class.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Java Review 3 Rem Collier. Java Wrapper Classes In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
POP3 Post Office Protocol v.3. Intro The Post Office Protocol (POP) is currently the most popular TCP/IP access and retrieval protocol. It implements.
Introduction 1 Lecture 7 Application Layer (FTP, ) slides are modified from J. Kurose & K. Ross University of Nevada – Reno Computer Science & Engineering.
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
Introduction 1-1 Chapter 2 FTP & Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Addison-Wesley March 2012 IC322 Fall.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
CSE401N: Computer Networks Lecture-5 Electronic Mail S. M. Hasibul Haque Lecturer Dept. of CSE, BUET.
Application Protocols: ELECTRONIC MAIL (SMTP, POP) CSNB534 Semester 2, 2007/2008 Asma Shakil.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
S OFTWARE D ESIGN Design Patterns 3 10/8/2015 Computer Science Department, TUC-N.
File Transfer Protocol (FTP)
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Lexi case study (Part 2) Presentation by Matt Deckard.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
1 CSC/ECE 517 Fall 2010 Lec. 3 Overview of Eclipse Lectures Lecture 2 “Lecture 0” Lecture 3 1.Overview 2.Installing and Running 3.Building and Running.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
P.O.P. A presentation brought to you by Thomas. Topics Introduction General Information Area of use Functionality The alternative way POP3 vs. IMAP Conclusion.
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
OOP with Java, David J. Barnes/Eric Jul Defining Classes1 Object State and Complexity Objects maintain a state. State is represented by a set of attributes.
STRATEGY PATTERN. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Slides based on Carey Williamson’s: FTP & SMTP1 File Transfer Protocol (FTP) r FTP client contacts FTP server at port 21, specifying TCP as transport protocol.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The State Design Pattern A behavioral design pattern. Shivraj Persaud
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
Spring 2006 CPE : Application Layer_ 1 Special Topics in Computer Engineering Application layer: Some of these Slides are Based on Slides.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
4/16/2018 Design Patterns David Talby.
Strategy Design Pattern
State pattern – A logical ‘Finite State Machine’
Algorithms and Data Structures
Control Statement Examples
null, true, and false are also reserved.
State Design Pattern 1.
COMPUTER 2430 Object Oriented Programming and Data Structures I
DESIGN PATTERNS : State Pattern
Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract, Computer,
Introduction to Design Patterns
Software Design Lecture : 39.
Chapter 2 Application Layer
Software Design Lecture 11.
Presentation transcript:

Zahra Moslehi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design pattern Course Fall 2010 Design Pattern Course

I NTENT Allow an object to alter its behavior when its internal state changes Also known as: Objects for States

M OTIVATION The class TCPConnection delegates all state-specific requests to this state object TheTCPState class declares an interface common to all classes that represent different operational states the classes TCPEstablished and TCPClosed implement behavior particular to theEstablished and Closed states of TCPConnection

S TRUCTURE

A PPLICABILITY An object's behavior depends on its state An object must change its behavior at run-time depending on that state Operations have large, multipart conditional statements that depend on the object's state

P ARTICIPANTS Context (TCPConnection) maintains an instance of a ConcreteState subclass that defines the current state. clients don't have to deal with the State objects directly State (TCPState) defines an interface for encapsulating the behavior associated with a particular state of the Context. ConcreteState subclasses (TCPEstablished, TCPListen, TCPClosed) each subclass implements a behavior associated with a state of the Context.

C ONSEQUENCES Benefits Puts all behavior associated with a state into one object new states and transitions can be added easily by defining new subclasses State objects can be shared It makes state transitions explicit Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes It eliminates the necessity for a set of long, look-alike conditional statements scattered through the program’s code. in the process, simplifies and clarifies the program

C ONSEQUENCES ( CONT ) Liabilities Increased number of objects

I MPLEMENTATION How can the state object store its state elsewhere? Have the Context store this data and pass it to the state object (a push model) Have the Context store this data and have the state object retrieve it when needed ( a pull model)

Consider a simplified version of the Post Office Protocol used to download from a mail server Simple POP (SPOP) supports the following command: USER username The USER command with a username must be the first command issued PASS password The PASS command with a password or the QUIT command must come after USER. If the username and password are valid, then the user can use other commands. S AMPLE CODE (E XAMPLE 1)

LIST The LIST command returns the size of all messages in the mail box If the optional message number is specified, then it returns the size of that message. RETR The RETR command retrieves all message in the mail box If the optional message number is specified, then it retrieves that message. QUIT The QUIT command updates the mail box to reflect transactions taken, then logs the user out. S AMPLE CODE (E XAMPLE 1)

Here's a version of an SPop class without using the State pattern: public class SPop { static final int QUIT = 1; static final int HAVE_USER_NAME = 2; static final int START = 3; static final int AUTHORIZED = 4; private int state = START; String userName; String password; S AMPLE CODE (E XAMPLE 1)

public void user(String userName) { switch (state) { case START: { this.userName = userName; state = HAVE_USER_NAME; break; } default: { // Invalid command sendErrorMessageOrWhatEver(); endLastSessionWithoutUpdate(); userName = null; password = null; state = START; } S AMPLE CODE (E XAMPLE 1)

public void pass(String password) { switch (state) { case HAVE_USER_NAME: { this.password = password; if (validateUser()) state = AUTHORIZED; else { sendErrorMessageOrWhatEver(); userName = null; password = null; state = START; } default: { // Invalid command sendErrorMessageOrWhatEver(); endLastSessionWithoutUpdate(); state = START; }... S AMPLE CODE (E XAMPLE 1)

Now let's use the State pattern! S AMPLE CODE (E XAMPLE 1)

a push model public class SPopState { public SPopState user(String userName) {default action here} public SPopState pass(String password) {default action here} public SPopState list(int messageNumber) {default action here} public SPopState retr(int messageNumber) {default action here} public SPopState quit() {default action here} } public class Start extends SPopState { public SPopState user(String userName) { return new HaveUserName(userName); } S AMPLE CODE (E XAMPLE 1)

public class HaveUserName extends SPopState { String userName; public HaveUserName(String userName) { this.userName = userName; } public SPopState pass(String password) { if (validateUser(userName, password) return new Authorized(userName); else return new Start(); } S AMPLE CODE (E XAMPLE 1)

public class SPop { private SPopState state = new Start(); public void user(String userName) { state = state.user(userName); } public void pass(String password) { state = state.pass(password); } public void list(int messageNumber) { state = state.list(messageNumber); }... } S AMPLE CODE (E XAMPLE 1)

a pull model public class SPop { private SPopState state = new Start(); String userName; String password; public String getUserName() {return userName;} public String getPassword() {return password;} public void user(String newName) { this.userName = newName ; state.user(this); }... } S AMPLE CODE (E XAMPLE 1)

public class HaveUserName extends SPopState { public SPopState user(SPop mailServer) { String userName = mailServer.getUserName();... }... } S AMPLE CODE (E XAMPLE 1)

S AMPLE CODE (E XAMPLE 2)

S AMPLE CODE (E XAMPLE 3) S1 S2 a a/b b

class FSM { State state; public FSM(State s) { state = s; } public void move(char c) { state = state.move(c); } public boolean accept() { return state.accept();} } public interface State { State move(char c); boolean accept(); } S AMPLE CODE (E XAMPLE 3)

class State1 implements State { static State1 instance = new State1(); private State1() {} public State move (char c) { switch (c) { case 'a': return State2.instance; case 'b': return State1.instance; default: throw new IllegalArgumentException(); } public boolean accept() {return false;} } S AMPLE CODE (E XAMPLE 3)

class State2 implements State { static State2 instance = new State2(); private State2() {} public State move (char c) { switch (c) { case 'a': return State1.instance; case 'b': return State1.instance; default: throw new IllegalArgumentException(); } public boolean accept() {return true;} } S AMPLE CODE (E XAMPLE 3)

class AbstractTool is function moveTo(point) is input: the location point the mouse moved to (this function must be implemented by subclasses) function mouseDown(point) is input: the location point the mouse is at (this function must be implemented by subclasses) function mouseUp(point) is input: the location point the mouse is at (this function must be implemented by subclasses) S AMPLE CODE (E XAMPLE 4)

subclass PenTool of AbstractTool is last_mouse_position := invalid mouse_button := up function moveTo(point) is input: the location point the mouse moved to if mouse_button = down (draw a line from the last_mouse_position to point) last_mouse_position := point function mouseDown(point) is input: the location point the mouse is at mouse_button := down last_mouse_position := point function mouseUp(point) is input: the location point the mouse is at mouse_button := up S AMPLE CODE (E XAMPLE 4)

subclass SelectionTool of AbstractTool is selection_start := invalid mouse_button := up function moveTo(point) is input: the location point the mouse moved to if mouse_button = down (select the rectangle between selection_start and point) function mouseDown(point) is input: the location point the mouse is at mouse_button := down selection_start := point function mouseUp(point) is input: the location point the mouse is at mouse_button := up S AMPLE CODE (E XAMPLE 4)

class Cursor is current_tool := new PenTool function moveTo(point) is input: the location point the mouse moved to current_tool.moveTo(point) function mouseDown(point) is input: the location point the mouse is at current_tool.mouseDown(point) function mouseUp(point) is input: the location point the mouse is at current_tool.mouseUp(point) function usePenTool() is current_tool := new PenTool function useSelectionTool() is current_tool := new SelectionTool S AMPLE CODE (E XAMPLE 4)

R ELATED P ATTERNS Flyweight Singleton

Thanks for your attention؟