Design Patterns. Command. Oliver Haase

Size: px
Start display at page:

Download "Design Patterns. Command. Oliver Haase"

Transcription

1 Design Patterns Command Oliver Haase 1

2 Description Purpose: Encapsulate a command as an object. Allows to dynamically configure an invoker with a command object. Invoker can invoke command without knowing its specifics, nor the receiver of the command. Also Known As: Action, Transaction 2

3 Motivation & Remarks Most widely known application of the command pattern: event listeners for GUI programming Remark: Command pattern is the object-oriented counterpart of function pointers in procedural languages Remark II: If the command object contains only one operation, function pointers can be considered more lightweight and thus more appropriate 3

4 Remarks Remark III: In C#, a function pointer is called a delegate. Example: // C# public delegate boolean FUNC(object x, object y); public boolean Compare (object x, object y) {... public boolean contains (object x, object[ ] field) { CMP_Func myfuncobj = new FUNC(Compare) ; foreach ( object obj in field ) f if ( myfuncobj ( obj, x ) ) return true; return false; 4

5 Motivation In Java Swing, when a JButton is pressed, the button invokes the actionperformed method of a pre-registered ActionListener command object. The ActionListener interface contains only the actionperformed method. an ActionListener command object can be registered using the JButton's addactionlistener method. 5

6 Another Remark Remark IV: In Java, an anonymous class might be a good choice to avoid the fully-fledged declaration of a class for a single method that is called only once: JButton submitbutton = new JButton ( "submit" ) ; submitbutton.addactionlistener (new ActionListener( ) { public void actionperformed( ActionEvent e) { ) ; // do whatever is needed to submit 6

7 Sample Structure MyApplication JButton actionlistener ActionListener actionperformed() MyModel action() MyActionListener model actionperformed() model.action() 7

8 Applicability Use the command pattern if you want to dynamically configure an object with an action; support undo functionality; keep a log of the executed actions so they can be redone in case of a crash; model a complex transaction; in this case the encapsulation of the transaction in a command object reduces code dependencies. 8

9 General Structure creates a concrete command object and passes the receiver into it. Client invokes the command through the Command interface. Invoker command Command execute() declares interface for command invocation Receiver action() ConcreteCommand receiver execute() knows how to perform the action. receiver.action() defines action to be performed defines receiver 9

10 Interactions Client creates concrete command object and determines the receiver Invoker stores the concrete command object Invoker executes a request by invoking the command object's execute operation If a command can be undone, the command object stores the receiver's original state so it can be restored later The concrete command object implements the request by calling some operation at the receiver object 10

11 Undo & Redo How to implement chains of undos and redos: provide an additional undo operation in the Command interface Invoker stores the concrete command object in each ConcreteCommand class, store the state before execution of the execute operation; this may include: all parameters for the action performed by the receiver all state information of the receiver that might change due to the execution of the action ( memento pattern) receiver must allow command object to restore receiver's original state 11

12 Undo & Redo How to implement chains of undos and redos: Client stores all executed commands in a command history depth of command history determines number of possible undo/redo steps command objects are copied before insertion into command history 12

13 Consequences Command pattern decouples the entity that invokes a request (Invoker) from the one that knows how to implement it (Command) Command objects can be manipulated (configured) and extended as any other object. Command objects can be composed to build macro objects. For this purpose, the composite pattern can be employed. New command objects can easily be created without modifying existing classes. Command objects can be replaced at runtime useful, e.g., for context-sensitive menus 13

14 Related Patterns The Composite pattern can be used to build macro commands (in which case the MacroCommand class doesn't point to a receiver object) If a command needs to store the receiver's state (undo), it can use the Memento pattern If a command object needs to be copied before being inserted into the command history, then it behaves like a Prototype 14

15 Iterator 15

16 Purpose Give sequential access to the individual elements of a complex object structure without revealing its internals. Also known as: Cursor 16

17 Sample Structure Client List iterator() Iterator hasnext() next() Vector iterator() ArrayList iterator() ArrayListIterator hasnext() next() VectorIterator hasnext() next() 17

18 Consequences / Benefits Using an iterator, a structure can be traversed multiple times at the same time; in different orders without changing the structure s interface. 18

19 General Structure defines operation to create iterator instance uses concrete aggregate through Aggregate and concrete iterator through Iterator interface. Client defines interface to access and traverse elements of an aggregate Aggregate createiterator() Iterator hasnext() next() ConcreteAggregate createiterator() ConcreteIterator hasnext() next() creates concrete iterator return new ConcreteIterator() implements Iterator interface stores current position of traversal 19

20 Privileged Access Iterators usually have privileged access to the elements of an aggregate. This can be achieved through friend class concept (C++): make iterator friend of aggregate non-static member classes (Java): Beware, publication of an inner class instance implicitly also publishes outer instance. 20

21 Robust Iterators It can be dangerous to modify an aggregate while it is being traversed robust iterators don't get affected possible techniques: iterator works on deep copy of aggregate potentially out-dated snapshot iterator is registered with aggregate, aggregate notifies iterators about modifications 21

22 Java Iterator Interface the Java collection framework uses the Iterator pattern each implementation of Collection<E> implements the interface Iterable<E>: interface Iterable<E> { Iterator<E> iterator(); interface Iterator<E> { boolean hasnext(); E next(); void remove(); custom aggregate classes can and should also implement Iterable and provide appropriate iterators. 22

23 Java Iterator Interface sample usage: for ( Iterator<ElementType> it = aggregate.iterator(); it.hasnext(); ) { iterator.next().use(); or, as a for-each loop: for ( ElementType element : aggregate ) { element.use(); the for-each loop is internally translated into the above for loop. 23

24 Java Iterator Interface What s wrong with the following code snipplet? public static void usevector(vector<t> vector) { for (T element : vector) element.use(); Not threadsafe, because vector might get modified while being iterated! - This is true even though Vector is a synchronized collection. Concurrent modification of underlying collection may result in ConcurrentModificationException iterator fail-fast, but on a best effort basis, i.e. applications must not rely on it 24

25 Java Iterator Interface Possible Solutions: 1. copy vector, iterate on the copy performance cost, iterates over a potentially outdated snapshot 2. client-side locking: public static void usevector(vector<t> vector) { synchronized ( vector ) { for (T element: vector) element.use(); prevents other threads from modifying vector during iteration, but also from accessing vector at all! 25

26 Java Iterator Interface What s wrong with the following code snipplet? public static void filtervector(vector<t> vector) { for (T element : vector) if (!element.isvalid() ) vector.remove(element); Same thread modifies vector while being iterated ConcurrentModificationException! 26

27 Java Iterator Interface Solution: modify vector through iterator, not directly. public static void filtervector(vector<t> vector) { for (Iterator<T> it = vector.iterator(); it.hasnext(); ) if (! it.next().isvalid() ) it.remove(); 27

28 Hidden Iterators What s wrong with the following class? public class HiddenIterator { private final Set<Integer> set = new HashSet<Integer>(); public synchronized void add(integer i) { set.add(i); public synchronized void remove(integer i) { set.remove(); public void addtenthings() { Random r = new Random(); for ( int i = 0; i < 10; i++ ) add(r.nextint()); System.out.println( Added ten elements to + set); set.tostring() contains a hidden iterator not threadsafe! 28

29 Hidden Iterators The following methods that operate on collections all contain hidden iterators: tostring() hashcode() equals() called if collection is used as key or element of another collection containsall() removeall() retainall() constructors that take collections as arguments 29

30 Iterating Concurrent Collections Since Java 5.0, Collection framework contains several concurrent collections that allow for concurrent access while still being threadsafe, including: ConcurrentHashMap ( lock striping) CopyOnWriteArrayList ( new copy for each modification) ConcurrentLinkedQueue ( lock striping) Iterators on concurrent collections are weakly consistent traverse elements as they were at time of iterator construction cannot throw ConcurrentModificationException! 30

31 Related Patterns Iterators are often used for recursive structures such as Composita For iterator creation, aggregate defines a factory method Iterators can use the Memento pattern to store the state of an iteration. 31

32 Visitor 32

33 Purpose Separate algorithm from the object structure upon which it operates. 33

34 Motivation Consider the following list structure: Client List sum(): int chars(): String NIL sum(): int chars(): String Element tail IntElement head: int sum(): int chars: String CharElement head: char sum(): int chars: String [compare: J. Bloch, Effective Java, 2nd Edition, item 43: Return empty arrays or collections, not null] 34

35 Motivation public interface List { int sum(); String // even stateless public class Nil implements List public String chars() { return public int sum() { return 0; public abstract class Element implements List { protected final List tail; protected Element(List tail) { this.tail = tail; 35

36 public class IntElement extends Element { private final int head; public IntElement(int number, List tail) { super(tail); head = public String chars() { return public int sum() { return head + public class CharElement extends Element { private char head; public CharElement(char character, List tail) { super(tail); head = public String chars() { return head + public int sum() { return tail.sum(); 36

37 Motivation Sample Usage: public class Client { public static void main(string[] args) { List l = new IntElement(4, new CharElement('b', new CharElement('a', new IntElement(3, new Nil())))); System.out.println("Sum: " + l.sum()); System.out.println("Characters: " + l.chars()); 37

38 Motivation Problem: Introduction of a new operation, e.g. boolean contains (char c); requires modification of List interface IntElement class CharElement class Generally, of all classes of the object structure. 38

39 Key Idea Idea: Separate operations (sum(), chars(), ) into visitor classes that traverse the object structure. Prepare object structure to let operations traverse it. Add an accept(visitor) method to each element type. In each specific visitor, provide one visit(elementtype) operation per ElementType. To visit an element, visitor calls element s accept operation which in turn calls the visitor s appropriate visit(elementtype) operation. 39

40 Sample Structure Client List accept(visitor) Visitor visit(nil) visit(intelement) visit(charelement) NIL accept(visitor) Element tail SumVisitor visit(nil) visit(intelement) visit(charelement) CharVisitor visit(nil) visit(intelement) visit(charelement) IntElement head: int accept(visitor) CharElement head: char accept(visitor) 40

41 Sample Implementation public interface List { void accept(visitor // even stateless public class Nil implements List public void accept(visitor visitor) { visitor.visit(this); public abstract class Element implements List { protected List tail; protected Element(List tail) { this.tail = tail; public List gettail() { return tail; 41

42 Sample public class IntElement extends Element { private int head; public IntElement(int number, List tail) { super(tail); head = number; public int gethead() { return public void accept(visitor visitor) { visitor.visit(this); public interface Visitor { void visit(nil list); void visit(intelement list); void visit(charelement list); 42

43 Sample // must be run thread-confined public class SumVisitor implements Visitor { private int sum = public void visit(nil list) public void visit(intelement list) { sum += list.gethead(); public void visit(charelement list) { list.gettail().accept(this); public int getsum() { return sum; Please note: visitor can (and sometimes must) store state information. 43

44 Sample Implementation Sample Usage: public class Client { public static void main(string[] args) { List l = new IntElement(4, new CharElement('b', new CharElement('a', new IntElement(3, new Nil())))); SumVisitor sv = new SumVisitor(); l.accept(sv); System.out.println("Summe: " + sv.getsum()); CharsVisitor cv = new CharsVisitor(); l.accept(cv); System.out.println("Summe: " + cv.getchars()); 44

45 General Structure declares an overloaded visit operation for each concrete element type. defines accept operation with a visitor as argument. Client Visitor visit(concreteelementa) visit(concreteelementb) Element accept(visitor) implements accept operation, usually by calling visitor s appropriate visit operation. ConcreteElementA accept(visitor) ConcreteElementB accept(visitor) ConcreteVisitor visit(concreteelementa) visit(concreteelementb) provides implementation for each overloaded visit operation can store state information provides operation to retrieve final state Please note: Concrete elements need not have a common supertype. 45

46 Consequences of Modifications w/o visitor pattern with visitor pattern modify operation adapt all structural classes adapt only affected visitor modify object structure adapt only affected structural class adapt all visitor classes Visitor pattern is beneficial if object structure is more stable than operations on it. 46

47 Advanced Considerations The interaction sequence :Client v: ConcreteVisitor e:concreteelement e.accept(v) visit(this) might seem awkward. It is only necessary, because most OO languages (including Java and C#) support only single dispatch rather than double dispatch. 47

48 Advanced Considerations Desirable: in client, call visitor s appropriate overloaded visit operation, depending on element type :Client v: ConcreteVisitor e:concreteelement v.visit(e) doube dispatch: selection of visit depends on both e s type and v s runtime type 48

49 Advanced Considerations single dispatch polymorhism: method call v.visit(e) depends on v s runtime type, but only on e s static type. :Client v: ConcreteVisitor e:concreteelement e.accept(v) use single dispatch polymorhism to call correct e s accept method visit(this) use overloading to call correct visit method. 49

50 Advanced Considerations If client inspects the runtime type of an element, it can directly call the visitor s appropriate visit operations without the indirection via the element's accept operation:... if ( l instanceof Nil ) { v.visit((nil) list); if ( l instanceof IntElement ) { v.visit((intelement) list); if ( l instanceof CharElement ) { v.visit((charelement) list); 50

51 Advanced Considerations This task can be placed into visitor: public abstract class Visitor { public final void visit(list list) { if ( list instanceof Nil ) { visit((nil) list); if ( list instanceof IntElement ) { visit((intelement) list); if ( list instanceof CharElement ) { visit((charelement) list); abstract public void visit(nil list); abstract public void visit(intelement list); abstract public void visit(charelement list); 51

52 Advanced // must be run thread-confined public class SumVisitor extends Visitor { private int sum = 0; public void visit(nil list) { public void visit(intelement list) { sum += list.gethead(); visit(list.gettail()); public void visit(charelement list) { visit(list.gettail()); public int getsum() { return sum; 52

53 Advanced Considerations Now, list structure does not need accept method any more: public interface List { public class Nil implements List { public abstract class Element implements List { protected List tail; protected Element(List tail) { this.tail = tail; public List gettail() { return tail; 53

54 Advanced public class IntElement extends Element { private int head; public IntElement(int number, List tail) { super(tail); head = number; public int gethead() { return head; public class Client { public static void main(string[] args) { List l = new IntElement(4, new CharElement('b', new CharElement('a', new IntElement(3, new Nil())))); SumVisitor sv = new SumVisitor(); sv.visit(l); System.out.println("Summe: " + sv.getsum()); CharsVisitor cv = new CharsVisitor(); cv.visit(l); System.out.println("Summe: " + cv.getchars()); 54

55 Even More Advanced Considerations With introspection, the Visitor base class can do without the switch: public abstract class Visitor { final public void visit(list list) { Object[] os = {list; Class<?>[] cs = {list.getclass(); try { this.getclass().getmethod("visit", cs).invoke(this, os); catch ( Exception e) {... abstract public void visit(nil list); abstract public void visit(intelement list); abstract public void visit(charelement list); 55

Design Patterns and Frameworks Command

Design Patterns and Frameworks Command Design Patterns and Frameworks Command Oliver Haase Oliver Haase Emfra Command 1/13 Description Classification: Object-based behavioral pattern Purpose: Encapsulate a command as an object. Allows to dynamically

More information

The Visitor Pattern. Object interfaces are fixed and diverse, Need to allow new operations, without coupling.

The Visitor Pattern. Object interfaces are fixed and diverse, Need to allow new operations, without coupling. The Visitor Pattern Visitor Pattern represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

More information

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Iterator Pattern George Blankenship

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Iterator Pattern George Blankenship CSCI 253 Object Oriented Design: Iterator Pattern George Blankenship George Blankenship 1 Creational Patterns Singleton Abstract factory Factory Method Prototype Builder Overview Structural Patterns Composite

More information

Linked List Nodes (reminder)

Linked List Nodes (reminder) Outline linked lists reminders: nodes, implementation, invariants circular linked list doubly-linked lists iterators the Java foreach statement iterator implementation the ListIterator interface Linked

More information

Design Patterns. Decorator. Oliver Haase

Design Patterns. Decorator. Oliver Haase Design Patterns Decorator Oliver Haase 1 Motivation Your task is to program a coffee machine. The machine brews plain coffee, coffee with cream, sugar, sweetener, and cinnamon. A plain coffee costs 0,90,

More information

G51PGP Programming Paradigms. Lecture OO-14 More Design Patterns And Java Examples

G51PGP Programming Paradigms. Lecture OO-14 More Design Patterns And Java Examples G51PGP Programming Paradigms Lecture OO-14 More Design Patterns And Java Examples 1 Last lecture Design patterns Creational patterns Singleton Factory more this lecture 2 Reminder: Sub-type polymorphism

More information

Object Oriented Design & Patterns. Part 1

Object Oriented Design & Patterns. Part 1 Object Oriented Design & Patterns Part 1 1 Design Patterns Derived from architectural patterns: rules for design of buildings describe common problems, solutions to those problems OO design patterns convenient

More information

6.005 Elements of Software Construction Fall 2008

6.005 Elements of Software Construction Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements

More information

BEHAVIORAL DESIGN PATTERNS

BEHAVIORAL DESIGN PATTERNS BEHAVIORAL DESIGN PATTERNS BEHAVIORAL DESIGN PATTERNS Identifies common communication patterns between objects that realize these patterns Describes the objects and classes interact and divide responsibilities

More information

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011 Design Patterns Lecture 2 Manuel Mastrofini Systems Engineering and Web Services University of Rome Tor Vergata June 2011 Structural patterns Part 2 Decorator Intent: It attaches additional responsibilities

More information

SDC Design patterns GoF

SDC Design patterns GoF SDC Design patterns GoF Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating

More information

Collections and Iterators. Collections

Collections and Iterators. Collections Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CS180 Recitation. More about Objects and Methods

CS180 Recitation. More about Objects and Methods CS180 Recitation More about Objects and Methods Announcements Project3 issues Output did not match sample output. Make sure your code compiles. Otherwise it cannot be graded. Pay close attention to file

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

List ADT. Announcements. The List interface. Implementing the List ADT

List ADT. Announcements. The List interface. Implementing the List ADT Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as

More information

Object-Oriented Oriented Programming Command Pattern. CSIE Department, NTUT Woei-Kae Chen

Object-Oriented Oriented Programming Command Pattern. CSIE Department, NTUT Woei-Kae Chen Object-Oriented Oriented Programming Command Pattern CSIE Department, NTUT Woei-Kae Chen Command: Intent Encapsulate a request as an object thereby letting you parameterize clients with different requests

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

Synchronization SPL/2010 SPL/20 1

Synchronization SPL/2010 SPL/20 1 Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization

More information

» Access elements of a container sequentially without exposing the underlying representation

» Access elements of a container sequentially without exposing the underlying representation Iterator Pattern Behavioural Intent» Access elements of a container sequentially without exposing the underlying representation Iterator-1 Motivation Be able to process all the elements in a container

More information

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields

More information

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns EPL 603 TOPICS IN SOFTWARE ENGINEERING Lab 6: Design Patterns Links to Design Pattern Material 1 http://www.oodesign.com/ http://www.vincehuston.org/dp/patterns_quiz.html Types of Design Patterns 2 Creational

More information

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING Question No: 1 ( Marks: 1 ) - Please choose one Classes like TwoDimensionalShape and ThreeDimensionalShape would normally be concrete,

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern Think of drawing/diagramming editors ECE450 Software Engineering II Drawing/diagramming editors let users build complex diagrams out of simple components The user can group components to form larger components......which

More information

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

The Strategy Pattern Design Principle: Design Principle: Design Principle:

The Strategy Pattern Design Principle: Design Principle: Design Principle: Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design

More information

Dr. Xiaolin Hu. Review of last class

Dr. Xiaolin Hu. Review of last class Review of last class Design patterns Creational Structural Behavioral Abstract Factory Builder Factory Singleton etc. Adapter Bridge Composite Decorator Façade Proxy etc. Command Iterator Observer Strategy

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Design Patterns Reid Holmes

Design Patterns Reid Holmes Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes GoF design patterns $ %!!!! $ "! # & Pattern vocabulary Shared vocabulary

More information

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 8.

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 8. Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Exercise Session 8 Tomas Hruz Today s Exercise Session Organisation Status of the projects (summary in

More information

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures Abstract Data Types (ADTs) Class #08: Linear Data Structures Software Design III (CS 340): M. Allen, 08 Feb. 16 An ADT defines a kind of computational entity: A set of objects, with possible values A set

More information

Design Pattern and Software Architecture: IV. Design Pattern

Design Pattern and Software Architecture: IV. Design Pattern Design Pattern and Software Architecture: IV. Design Pattern AG Softwaretechnik Raum E 3.165 Tele.. 60-3321 hg@upb.de IV. Design Pattern IV.1 Introduction IV.2 Example: WYSIWYG Editor Lexi IV.3 Creational

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Iterator 1 (part I) Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 26, 2013 Abstract These lecture notes are meant to be looked

More information

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

Overview of Java s Support for Polymorphism

Overview of Java s Support for Polymorphism Overview of Java s Support for Polymorphism Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt

More information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

Command Pattern. CS356 Object-Oriented Design and Programming November 13, 2014

Command Pattern. CS356 Object-Oriented Design and Programming   November 13, 2014 Command Pattern CS356 Object-Oriented Design and Programming http://cs356.yusun.io November 13, 2014 Yu Sun, Ph.D. http://yusun.io yusun@csupomona.edu Command Encapsulate requests for service from an object

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Java Review: Objects

Java Review: Objects Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation

More information

Last Lecture. Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/ Spring Semester, 2005

Last Lecture. Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/ Spring Semester, 2005 1 Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/6448 - Spring Semester, 2005 2 Last Lecture Design Patterns Background and Core Concepts Examples

More information

Command. Comp-303 : Programming Techniques Lecture 22. Alexandre Denault Computer Science McGill University Winter 2004

Command. Comp-303 : Programming Techniques Lecture 22. Alexandre Denault Computer Science McGill University Winter 2004 Command Comp-303 : Programming Techniques Lecture 22 Alexandre Denault Computer Science McGill University Winter 2004 April 1, 2004 Lecture 22 Comp 303 : Command Page 1 Last lecture... Chain of Responsibility

More information

EMBEDDED SYSTEMS PROGRAMMING More About Languages

EMBEDDED SYSTEMS PROGRAMMING More About Languages EMBEDDED SYSTEMS PROGRAMMING 2015-16 More About Languages JAVA: ANNOTATIONS (1/2) Structured comments to source code (=metadata). They provide data about the code, but they are not part of the code itself

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

CSE 219 COMPUTER SCIENCE III BEHAVIORAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY

CSE 219 COMPUTER SCIENCE III BEHAVIORAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY CSE 219 COMPUTER SCIENCE III BEHAVIORAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY Behavioral Design Pattern These design patterns are specifically concerned with communication

More information

Design Patterns Reid Holmes

Design Patterns Reid Holmes Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes GoF design patterns $ %!!!! $ "! # & Pattern vocabulary Shared vocabulary

More information

Page 1. Human-computer interaction. Lecture 1b: Design & Implementation. Building user interfaces. Mental & implementation models

Page 1. Human-computer interaction. Lecture 1b: Design & Implementation. Building user interfaces. Mental & implementation models Human-computer interaction Lecture 1b: Design & Implementation Human-computer interaction is a discipline concerned with the design, implementation, and evaluation of interactive systems for human use

More information

COSC 3351 Software Design. Design Patterns Behavioral Patterns (II)

COSC 3351 Software Design. Design Patterns Behavioral Patterns (II) COSC 3351 Software Design Design Patterns Behavioral Patterns (II) Spring 2008 Purpose Creational Structural Behavioral Scope Class Factory Method Adapter(class) Interpreter Template Method Object Abstract

More information

Design Patterns. SE3A04 Tutorial. Jason Jaskolka

Design Patterns. SE3A04 Tutorial. Jason Jaskolka SE3A04 Tutorial Jason Jaskolka Department of Computing and Software Faculty of Engineering McMaster University Hamilton, Ontario, Canada jaskolj@mcmaster.ca November 18/19, 2014 Jason Jaskolka 1 / 35 1

More information

Iterator pattern. Acknowledgement: Eric Braude

Iterator pattern. Acknowledgement: Eric Braude Iterator pattern Acknowledgement: Eric Braude Let s try this Data structures: l Array l Binary Tree l Vector l Linked list l Hash table Algorithm: l Sort l Find l Merge How many permutations to develop/maintain?

More information

JVA-103. Java Programming

JVA-103. Java Programming JVA-103. Java Programming Version 8.0 This course teaches programming in the Java language -- i.e. the Java Standard Edition platform. It is intended for programmers with experience in languages other

More information

BlockingArrayQueue.java. Page 1

BlockingArrayQueue.java. Page 1 1 //BlockingArrayQueue.java 2 //Template blocking queue class, implemented with emulated circular array. 3 //Programmer: Randy Miller 4 //Last modification: April 13, 2015 5 6 7 8 import java.util.arraylist;

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

M257 Past Paper Oct 2008 Attempted Solution

M257 Past Paper Oct 2008 Attempted Solution M257 Past Paper Oct 2008 Attempted Solution Part 1 Question 1 A version of Java is a particular release of the language, which may be succeeded by subsequent updated versions at a later time. Some examples

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Encapsulation, Publication, Escape Data Encapsulation One of the approaches in object-oriented programming is to use data encapsulation

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Design for reuse. Design patterns for reuse

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Design for reuse. Design patterns for reuse Principles of Software Construction: Objects, Design, and Concurrency Part 1: Design for reuse Design patterns for reuse Charlie Garrod Bogdan Vasilescu School of Computer Science 1 Administrivia Homework

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Brief Note on Design Pattern

Brief Note on Design Pattern Brief Note on Design Pattern - By - Channu Kambalyal channuk@yahoo.com This note is based on the well-known book Design Patterns Elements of Reusable Object-Oriented Software by Erich Gamma et., al.,.

More information

S. No TOPIC PPT Slides

S. No TOPIC PPT Slides S. No TOPIC PPT Slides Behavioral Patterns Part-I introduction UNIT-VI 1 2 3 4 5 6 7 Chain of Responsibility Command interpreter Iterator Reusable points in Behavioral Patterns (Intent, Motivation, Also

More information

Homework 3 Semantic Analysis. Remi Meier Compiler Design

Homework 3 Semantic Analysis. Remi Meier Compiler Design Homework 3 Semantic Analysis Remi Meier Compiler Design 28.10.2015 1 Compiler phases Javali Compiler x86 Assembly IR IR Front-end Optimizations Back-end Machine independent Machine dependent Lexical Analysis

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline :: Module Title Duration : Intro to JAVA SE7 and Programming using JAVA SE7 : 9 days Course Description The Java SE 7 Fundamentals course was designed to enable students with little or no programming experience

More information

Object Oriented Paradigm

Object Oriented Paradigm Object Oriented Paradigm Ming-Hwa Wang, Ph.D. Department of Computer Engineering Santa Clara University Object Oriented Paradigm/Programming (OOP) similar to Lego, which kids build new toys from assembling

More information

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout 1 Last update: 2 November 2004 Trusted Components Reuse, Contracts and Patterns Prof. Dr. Bertrand Meyer Dr. Karine Arnout 2 Lecture 5: Design patterns Agenda for today 3 Overview Benefits of patterns

More information

Practice exam for CMSC131-04, Fall 2017

Practice exam for CMSC131-04, Fall 2017 Practice exam for CMSC131-04, Fall 2017 Q1 makepalindrome - Relevant topics: arrays, loops Write a method makepalidrome that takes an int array, return a new int array that contains the values from the

More information

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10 Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Exercise Session 10 Today s Exercise Session Pattern of the Day Proxy Quizzes 2 Proxy Pattern Structural

More information

An Introduction to Patterns

An Introduction to Patterns An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1 What is a Pattern? - 1 Work on software development patterns stemmed from work on patterns from building architecture

More information

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued) MBSE - 2.1 Design Patterns and Architecture 1 2.1 Design Patterns and Architecture (continued) 1. Introduction 2. Model Construction 2.1 Design Patterns and Architecture 2.2 State Machines 2.3 Timed Automata

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Object-Oriented Programming Intro Department of Computer Science University of Maryland, College Park Object-Oriented Programming (OOP) Approach to improving software

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued) MBSE - 2.1 Design Patterns and Architecture 1 2.1 Design Patterns and Architecture (continued) 1. Introduction 2. Model Construction 2.1 Design Patterns and Architecture 2.2 State Machines 2.3 Abstract

More information

Design Patterns Revisited

Design Patterns Revisited CSC 7322 : Object Oriented Development J Paul Gibson, A207 /~gibson/teaching/csc7322/ Design Patterns Revisited /~gibson/teaching/csc7322/l11-designpatterns-2.pdf 2013: J Paul Gibson TSP: Software Engineering

More information

CSE331 Fall 2014, Final Examination December 9, 2014 Please do not turn the page until 2:30. Rules:

CSE331 Fall 2014, Final Examination December 9, 2014 Please do not turn the page until 2:30. Rules: CSE331 Fall 2014, Final Examination December 9, 2014 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 4:20. There are 156 (not 100) points,

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Iterator 1 (part I) Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 26, 2013 Abstract These lecture notes are meant to be looked

More information

Java SE 8 Programming

Java SE 8 Programming Oracle University Contact Us: +52 1 55 8525 3225 Java SE 8 Programming Duration: 5 Days What you will learn This Java SE 8 Programming training covers the core language features and Application Programming

More information

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition? IBS Software Services Technical Interview Questions Q1. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition

More information

Implementing Dynamic Data Structures

Implementing Dynamic Data Structures Chapter 16 Implementing Dynamic Data Structures Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN:

More information

Binghamton University. CS-140 Fall Dynamic Types

Binghamton University. CS-140 Fall Dynamic Types Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information