Professional Documents
Culture Documents
סיכום פתמ
סיכום פתמ
בית הספר למדעי המחשב
1
TO SOFTWARE ENGINEERING
Programming in binary…
Full of bugs!
Assembly Language
oGreat success!
sum:
popl %ebp
ret
Fortran
◦ IF-THEN-ELSE
◦ GOTO
◦ DO loops
◦ Etc.
o“Formula Translation”
oEncouraged the production of compilers that generate faster and more efficient code
So…
High-level languages
Complex software
More bugs
o The term used for the difficulty of writing useful and efficient computer programs
oOfficially abandoned
◦ Tools
◦ Modeling languages
◦ Programming languages
◦ Programming paradigms
◦ Etc.
oAt the beginning of the 21st century – only 34% are successful projects
Developer’s productivity
Development Effort
Size Example
בית הספר למדעי המחשב
15
1.2 Introduction To
Software Engineering
History
oIn the 1940s the instructions were wired to the computers – not flexible
◦ the title for the world's first conference on software engineering (1968)
History
Related Fields
Computer
Science
Theoretical
Applied
Quality
Assurance
Software
Computer
Engineering Engineering
Project
Systems Management
Engineering
Software Engineering
◦ Not uniformed
◦ Not regulated
Developing software that has a value General truths about the complexity, correctness,
Emphasis
to a user soundness and completeness of algorithms
knowledge technology
Fundamentals
mathematics
Physics, chemistry, Calculus
Methods
solid mathematical foundation models
Relatively cheap.
cost are relatively cheap.
בית הספר למדעי המחשב
23
Language
No code!
Core Activities
oRequirements
oDesign
oConstruction
oTesting
The Software
oDebugging Development
Cycle
oDeployment
oMaintenance
בית הספר למדעי המחשב
31
1. Gather requirements
4. Describe the interaction between these objects these steps over the time of
1. Gather requirements
1. Gather requirements
Gather Requirements
oFunctional requirements
◦ Features
oNon-Functional requirements
◦ Documentation / Help
Examples:
◦ Performance
the app MUST allow the user to solve a maze
◦ Security
Non-Functional requirements:
FURPS
oFunctional Requirements
◦ Features
oUsability Requirements
◦ Documentation, tutorials
oReliability Requirements
FURPS+
◦ Recovery, acceptable failure rates
• Design Requirements
• Programming language
oSupportability Requirements • Interface Requirements
• Physical Requirements
1. Gather requirements
oHow does the user accomplish a certain goal with our application
◦ Use case
oExample
Use Case
oWe have written the requirements (“the app must have this feature”)
in full context
◦ Scenario – How is it accomplished?
oPreconditions
oTriggers
oAlternative Scenarios
oPreconditions
oTriggers
◦ User’s request
◦ User logs in, System displays a menu, User selects “money withdrawal”, System registers the transaction,
oAlternative Scenarios
◦ System’s informs the user, System aborts the action, System displays a menu, etc.
oExamples
◦ Enroll a course
◦ Submit a paper
◦ Grade a paper
◦ Other machines…
Teacher Assistant
Student
Info-Net System
Admin
Lecturer
Staff
Dean
Admin Lecturer
Dean Staff
Secondary Actor
Editor
◦ As a paragraph
◦ As a list of steps
oExample:
◦ Scenario:
described from the perspective of a user
◦ Student logs in
Identifying Scenarios
oExamples
Log in
◦ Submit a paper
◦ View syllabus
Be concise
oThe System connects the server through HTTPS, and uses XML to submit the provided search
problem to be solved, then waits for a response, in the form of a Solution object
oExample:
◦ Student logs in
◦ …
oA diagram of several use cases and multiple actors at the same time
The Diagram
Wikipedia System
Create an article
«actor»
Visitor Search an article
Backup System
View an article
Contributor
Analytics System
View analytics
Administrator
1. Gather requirements
1. Gather requirements
moves
Character
User UI Maze
Generator
uses
solves
displays
Displayer
1. Gather requirements
Class Diagram
Conceptual Model
Character
creates
*
1
Maze creates
1..* (has)
Generator Maze
<<MazeGenerator>>
creates
<<IMaze>>
generate(): IMaze
Maze
Generator
- entry, exit: Position
- data: Integer[][]
Maze3D
- characters: Character[]
- formatMazeData () : String
This is a note
+ toString ()
Maze2D
Methodologies
oWithout
oLow overhead
oResponsive use
oNo testing no
Customer
oTiming
end
oHard to measure progress
oIt takes more time to fix bugs as the development time increases
oDuring implementation
◦ New requirements
The V model
◦ Verification / Validation
Software Prototyping
◦ Throwaway prototype
◦ Evolutionary prototype
◦ The construction of the prototype continues until the final version
Requirements
oAdvantages
Prototype
◦ Improved and increased user involvement = less time & costs
Review
oDisadvantages
◦ Insufficient analysis
◦ Excessive development time of the prototype Revise
oShould be responsive
oAdvantages
◦ Customer response
oDisadvantages
Iterative: +/-
oPros:
◦ Parallel development
◦ Ongoing deliveries
oCons:
◦ Management attention
oTime constraints
Spiral Model
oStages:
1. Identification
2. Design
3. Construct/Build
Phases of Spiral
oIdentification
oDesign
oConstruction/Build
Spiral: +/-
oPros:
oCons:
◦ Complex management
oComplex requirements
Agile Model
◦ Self-organization and motivation are important, as are interactions like co-location and pair
programming.
oWorking software
oCustomer collaboration
oResponding to change
Agile Process
oCan be used with any type of project, but more common in small-medium projects
oDetermine the various features the client would like the product to support
◦ Client selects the features for next build using cost-benefit analysis
◦ The proposed build is broken down into smaller pieces termed tasks
88
oThere is no overall design step before the various builds are constructed.
oTDD test cases are retained and utilized in all further integration testing
oStand-up meetings
89
SCRUM
◦ SCRUM master
oDeliverables: Sprint
Agile: +/-
oPros:
◦ Realistic
◦ Functionality developed rapidly
◦ Minimal rules
◦ The end result is the high-quality software in the least possible time duration and satisfied customer
◦ Flexible
oCons:
triple constraints:
Design Principles
Iterators,
etc.
o Encapsulation
Generalization of code
General Principles
◦ Don’t write speculative code, solve the problem you know to exist
Middle Man
class
Data
Code Smells
YOU MUST AVOID THEM!
o Duplicated code
o Contrived complexity
◦ Has very different responsibilities, which have nothing to do with each other
◦ Common for a procedural programmer that has leaned only the syntax
o Feature Envy
◦ Does very little except use all the methods of another class
o Inappropriate intimacy
◦ A class that has dependencies on implementation details of another class
o Freeloader
o Conditional complexity
o Downcasting
◦ Example, two subclasses that handle different inputs in the same way
o Multiple inheritance
◦ Harder to test…
o Data class
o Middle Man
◦ A class that delegates all of its work – cut the middle man
o Long method
◦ A method that has grown too large
◦ The name of a variable should reflect its function unless the function is obvious
◦ A method that returns more than what each of its callers needs
o Inconsistent names
o Pointless comments
o Lack of comments
◦ Where it is needed
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
14
oS
oO
oL
oI
oD
oS Car
+ break(double): void
oO + steer(double): void
oL
oI
oD
oS Car
+ break(double): void
oO + steer(double): void
oL RaceCar
+ break(double): void
oI + steer(double): void
oD
oS <<Car>>
+ break(double): void
oO + steer(double): void
oI … …
… …
} }
oS <<Car>>
+ break(double): void
oO + steer(double): void
+ boost(double): void
oL
oI
oD
oS <<Racer>> <<Car>>
+ boost(double): void
+ break(double): void
oO + deployParachute():void
+ steer(double): void
oL
RaceCar
oI
oD
oS <<Car>>
+ break(double): void
oO + steer(double): void
<<Racer>>
oL
+ deployParachute():void
oI
oD
oS
oO
Car V-engine
oL
oI
oD
oS
oO
Car <<Engine>>
oL
Turbo-
◦ Liskov Substitution Principle V-engine
engine
oI
oD
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
25
GRASP
Information Expert
Creator
MazeGenerator Maze
o Decoupling: the process of reducing these dependencies
o Cohesion: how focused is a class around a single responsibility
o We want high cohesion & low coupling
Controller
Business Controller UI
Pure Fabrication
Indirection
Indirection
Indirection
Object
Polymorphism
Common
Searcher
o Example:
Protected Variations
◦ Encapsulation
◦ Interfaces
◦ Etc.
The Design Patterns we will learn will help you to achieve these design principles and avoid code smells…
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
38
AN EXAMPLE
sort(…){ BubbleSorter
…
}
compare(Employee e1, Employee e2): int Dynamic binding…
s.sort(employees); s.sort(employees);
40
BubbleSorter QuickSorter
compare() // by age compare() // by salary compare() // by name compare() // by age compare() // by salary compare() // by name
MergeSorter
41
int compare(Employee e1, Employee e2){ int compare(Employee e1, Employee e2){
} }
} }
42
sort(…){
<<Sorter>> <<Comparator>>
} c.compare(arr[i],arr[i+1]) sort(Employee[] arr, Comparator c): void compare(Employee e1, Employee e2): int
43
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
Short History
Java editions
◦ For general purpose use on desktop PCs, servers and similar devices
◦ Java SE plus various APIs useful for client–server enterprise applications (mainly server side)
Why Java?
Write software on one platform and run it on virtually any other platform
5
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
6
C
libraries for a specific compiler
Machine Code:
• Harder to reuse code written in other
Machine Code:
• Threading
Code Libs
system services
What is a JVM?
JVM architecture
javac:
Compiler ByteCode
.super java/lang/Object
return
.end method
10
Source Code:
• A multiplatform architecture
bytecode
verifier Memory to run on a different system as
Java Runtime
Code
Scala
• A managed environment
• E.g. a garbage collection
11
12
JVM architecture
JDK
13
http://docs.oracle.com/javase/8/docs/
Java Files
◦ A runnable file
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
16
The JVM loads the .class file and searches for an entry point
18
19
HelloWorldApp.Java HelloWorldApp.class
.class public HelloWorldApp
.super java/lang/Object
C:\> javac HelloWorldApp.java
.method public static main : ([Ljava/lang/String;)V
javac .limit stack 10 This file
.limit locals 10 represents
C:\> java HelloWorldApp
The argument is
The JVM finds the main
Loads the class into memory We run the
method according to its the class file as
program runs.
static methods!
Thus the main has to be static
Now, the byte code (in the .class file) is being interpreted by the JVM
a.method1();
a.method2();
a.method3();
21
Introducing JIT!
JIT offers in runtime to compile parts of the code into native (machine) code
22
JIT can decide that it is better to compile the loop’s code and “inline” it n times
23
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
24
GC – Garbage Collector
The GC automatically frees objects that are not referenced by any pointer
26
GC – Garbage Collector
27
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
Hello World
System.out.println("Hello World!");
Conventions:
◦ Case sensitive
Hello World
System.out.println("Hello World!");
print();
Hello World
System.out.println("Hello World!");
print();
Hello World
System.out.println("Hello World!");
class the main is in??
b.print();
7
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
8
Data types
void - Void
10
Variables
Variable names must begin with a letter but can contain letters and digits
Examples:
double myAge=29.5;
double herAge;
herAge=myAge-4;
char yes='Y';
11
Constant variables
min=4; // error
12
Operators
x=20; y+=5;
x++; m=y%2;
13
◦ == (equal to)
◦ <, >, <=, >= (less, greater, less or equal, greater or equal)
◦ & (and)
◦ | (or)
◦ ^ (xor)
◦ ~ (not)
14
Boolean expressions
(true or false)
15
Control flow
◦ if (..) {…}
Iteration statements
16
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
17
Arrays
int[] pointers
19
Arrays as objects
for(int i=0;i<array1.length;i++)
System.out.println(array1[i]);
for(int i=0;i<array4.length;i++)
for(int j=0;j<array4[i].length;j++)
System.out.println(array4[i][j]);
20
Iterating an array
A nicer syntax:
for(int a : array1)
System.out.println(a);
for(int[] ar : array4)
for(int a : ar)
System.out.println(a);
21
Copying arrays
numbersCopy[0]=7;
System.out.println(numbersCopy[0]);
System.out.println(numbers[0]);
Output
22
Copying arrays
array6=new int[array5.length][array5[0].length];
for(int i=0;i<array5.length;i++)
for(int j=0;j<array5[i].length;j++)
array6[i][j]=array5[i][j];
23
Copying arrays
for(int i=0;i<7;i++)
Output
System.out.print(numbersCopy[i]+” ”);
0000234
24
JVM
Java Source
Java Byte Code input Interpret code that copies array
Code
Array copy compiled function
for(int i=0;i<array1.length;i++)
array2[i]=array1[i];
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
26
Strings
28
String - concatenating
String p="people";
29
Comparing Objects
◦ In other words, checks if they are pointing to the same location = referenced to the same
object
30
Comparing Strings
if(S1==S2)
else
System.out.println("not equal");
moshe moshe
if(S1.equals(S2))
s1 s2 System.out.println("equal");
else
31
Comparing Strings
◦ The string that invoked the method is saved in a special pool (hash table)
if(s1==s2)
System.out.println(“equal");
“david” “david”
else
System.out.println(“not equal"); intern() intern()
if(s1.intern()==s2.intern())
System.out.println(“equal"); O(1)
else
System.out.println(“not equal"); “david”
if(s1.intern()==s2.intern())
System.out.println(“equal");
String Pool
else
System.out.println(“not equal");
32
Comparing Strings
◦ The string that invoked the method is saved in a special pool (hash table)
if(s1==s2)
System.out.println(“equal");
“david” “david”
else
System.out.println(“not equal"); intern() intern()
if(s1.intern()==s2.intern())
System.out.println(“equal"); O(n)
else
System.out.println(“not equal"); “david”
??
if(s1.intern()==s2.intern())
else
System.out.println(“not equal");
33
Quiz…
String s2 = “hello”;
Does ?
◦ s1 == s2
◦ s1.intern() == s2.intern()
◦ s1.intern() == s2
◦ s2.intern() == s2
Intern in C#
◦ With each string creation the pool is checked for storing the string and a reference is kept
◦ The Intern() is a static method of the String class that returns this reference
string s1 = "MyTest";
string s2 = new StringBuilder().Append("My").Append("Test").ToString();
string s3 = String.Intern(s2);
35
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
36
String java="Java";
String java="Java";
char c = java.charAt(2);// v
38
◦ toLowerCase / toUpperCase
39
StringBuilder
for(int i=0;i<100;i++)
for(int i=0;i<100;i++)
40
Without StringBuilder
System.out.println(reversePalindrome);
Output
avaj evol I
41
With StringBuilder
*/
/*
sb.reverse(); // reverse it
System.out.println(sb);
Output
abbaB ilA
42
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
43
void main() {
RAM – Random Access Memory
Rectangle rect;
p1->Set(20, 45);
rect{
m_TopLeft,
p2->Set(50, 70);
rect.Set(p1, p2);
}
70 p1 = 86
82 bottomRight = 92
}
86 { m_x=20, m_y=45 }
92 { m_x=50, m_y=70 }
void main() {
RAM – Random Access Memory
Rectangle rect;
p1->Set(20, 45);
rect{
m_TopLeft = { 20, 45 }
p2->Set(50, 70);
rect.Set(p1, p2);
}
70 86
p1 = Null
74 p2 = Null
92 void Set(Point* topLeft, Point* bottomRight){
m_TopLeft = *topLeft;
82 bottomRight = 92
}
86 { m_x=20, m_y=45 }
92 { m_x=50, m_y=70 }
48
int x;
public MyInt(int x) {
this.x=x;
49
public static void add1(int x){x+=1;} public static void main(String[] args) {
int x=5;
} add2(myX);
add3(myX);
x.inc(); }
50
for(int i=0;i<as.length;i++)
◦ as[i]=new A();
for(A a : as)
◦ a=new A();
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
Recap…
A class is loaded only once while its instances can be as many as we whish
Recap…
An instance is created with “new” command
“new” Calls the class’s constructor
Members are called from objects
Static members are called from the class
public
class HelloWorld { public class Run {
public void print() { public static void main(String[] args) {
} h.print();
}
}
Recap…
We define A a;
◦ a.s();
◦ a.m();
◦ A.s();
◦ A.m();
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
7
5.2 Inheritance
Object’s methods:
Inheritance
extends
O:
this.super.super
Inheritance
Class A is a super-class of B:
public class A { public class B extends A{ Every Ctor must
private int x,y; public B(int x, int y) {
initialize
the A part.
public A(int x,int y){ super(x, y); super(x,y) must
Inheritance
this.x=x; b.super.super }
this.y=y; }
} A A b=new B(10,10);
x=10, y=10
}
}
implementad on class A
called from class B, x=11 y=11
Inheritance
this.x=x; b.super.super }
this.y=y; }
} A A b=new B(10,10);
x=10, y=10
@Override
getClass ?
b.super toString ? B b1=new B(11,11);
}
}
implementad on class A
called from class B, x=11 y=11
Inheritance
this.x=x; }
this.y=y;
Inheritance
System.out.println("1"); System.out.println("1d");
} }
System.out.println("2"); System.out.println("2d");
} }
System.out.println("3"); System.out.println("3d");
} }
} }
Dynamic Binding
All the methods in Java are like C++ virtual methods – dynamic binding!
class A{
public class A {
}
}
}
} cout<<"B"<<endl;
}
a.print(); // B
a->print(); // B
}
} }
};
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
17
Abstract classes
◦ It is left unimplemented
Abstract classes
String name;
this.name=name;
System.out.println("hello "+name);
Abstract classes
this.name=name;
System.out.println("wlcome "+name);
} }
Interfaces
<<I>>
<<I>>
<<I>>
<<I>>
interface
interface
Object interface
interface
extends implements
}
//...
}
//...
@Override
public void startTeaching() {
}
@Override
//guitarPlayer.startTeaching(); @Override
lecturer.startTeaching(); }
◦ They provide data and functionality common to all the derived classes
We use interfaces
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
26
Example
sorter.sort(…);
sort(:Comparable[])
sorter.sort(…);
Example
<<Sorter>> <<Comparable<T>>>
sort(:Comparable[])
compareTo(:T) : int
measureTime()
(T = String)
CommonSorter
String
sort(:Comparable[])
compareTo(:String) : int
measureTime()
Example
CommonSorter
sort(:Comparable[])
measureTime()
Example
<<Sorter>>
@Override
public long measureTime(Comparable<T>[] comparables) {
sort(comparables);
measureTime()
return System.currentTimeMillis()-time0;
}
CommonSorter }
sort(:Comparable[])
measureTime() public class BubbleSort<T> extends CommonSorter<T>{
@Override
//...
Bubble Sort Quick
MergeSort
Sort
if(comparables[i].compareTo(comparables[i+1]))>0)
switchCells(comparables[i],comparables[i+1]);
//...
Example
<<Sorter>> <<Comparable<T>>>
sort(:Comparable[])
compareTo(:T) : int
measureTime()
(T = String)
CommonSorter
String
sort(:Comparable[])
compareTo(:String) : int
measureTime()
String[] abc="B,D,A,F,E,C,G".split(",");
sorter.sort(abc);
}
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
T* t; public:
class Holder{
public: void set(Student
t; * t){ this->t = t; }
}; Employee*
public: get(){ return t; }
Holder<Employee> he;
};
Holder<int> hi;
} ((Employee)h.get()).work();
//...
public static void main(String[] args) {
h.set(new Student());
((Student)h.get()).study();
h.set(new Employee());
((Employee)h.get()).work();
public void set(Object t){ this.t=t;} public void set(T t){ this.t=t;}
} }
public static void main(String[] args) { public static void main(String[] args) {
hs.set(new Student());
((Student)h.get()).study();
Holder<Employee> he=new Holder<Employee>();
((Employee)h.get()).work(); he.get().work();
} }
hs.set(new Student());
hs.get().study();
he.set(new Employee());
he.get().work();
} hs.set(new Student());
hs.get().study();
//...
public static void main(String[] args) {
hs.get().study();
he.set(new Employee());
he.get().work();
Complied code:
public void set(T t){ this.t=t;} public void set(Object t){ this.t=t;}
} Syntax sugar }
Complied code:
public static void main(String[] args) { public static void main(String[] args) {
hs.get().study(); ((Student)h.get()).study();
he.get().work(); ((Employee)he.get()).work();
} }
Complied code:
public void set(T t){ this.t=t;} public void set(Object t){ this.t=t;}
} }
In addition:
• T t = new T();
• t.doSomething(); System.out.println((he.getClass()==hs.getClass()));
try {
throw new GenericException<Integer>();
catch(GenericException<Integer> e) {
System.err.println("Integer");
catch(GenericException<String> e) {
System.err.println("String");
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
12
6.2 Java8
IN INTERFACES(!)
System.out.println(str);
System.out.println(str);
}
}
@Override
public void record(InputStream in) {/*...*/}
@Override
Recorder.stdPrint(str);
}
}
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
16
JAVA 8
Lambda Expressions
// Anonymous class...
@Override
};
System.out.println(f.func("Hello World!"));
Lambda Expressions
FunctionalInterface f;
f=(String str)->{return new StringBuilder(str).reverse().toString();};
System.out.println(f.func("Hello World!"));
Lambda Expressions
FunctionalInterface f;
f=str->new StringBuilder(str).reverse().toString();
System.out.println(f.func("Hello World!"));
Lambda Expressions
It’s not (just) about the syntax, it’s about the paradigm!
◦ Laziness
◦ Parallelism
◦ out-of-order computations
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
22
JAVA.UTIL.*
Introduction
library
◦ Called containers
x.add(new Integer(1));// ok
x.add(2);// also ok
Useful Containers
Lists:
Example:
strings.add(“hello world”);
Sets:
Example:
strings.add(“hello world”);
boolean add(E e)
void clear()
boolean contains(Object o)
boolean containsAll(Collection<?> c)
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object o)
members.addAll(names);
<T> T[] toArray(T[] a)
Useful Containers
Maps example:
◦ LinkedHashMap
V get(K key)
void clear()
boolean isEmpty()
V remove(Object key)
Set<Map.Entry<K,V>> entrySet()
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
32
Comparators
◦ Comparator
◦ Comparable
They are used in a strategy pattern to sort various objects in the containers
} }
Comparators
◦ Comparator
◦ Comparable
They are used in a strategy pattern to sort various objects in the containers
} }
Comparable
@Override
return salary-arg0.getSalary();
}…
for(Worker w : workers)
ArrayList with the
◦ It was implemented to compare salaries, thus, the array was sorted by the
salary field
return salary-arg0.getSalary();
}…
Collections.sort(workers);
Comparator
Comparator
@Override
return w0.getName().compareTo(w1.getName());
And use:
Collections.sort(workers, new NameComparator());
Comparator
Collections.sort(workers, new
Comparator<Worker>(){
@Override
return w0.getName().compareTo(w1.getName());
);
Collections.sort(workers,(w0,w1)->w0.getName().compareTo(w1.getName()));
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
43
Iterators
for(Worker w : workers)
System.out.println(w);
Iterator<Worker> it=workers.iterator();
while(it.hasNext())
System.out.println(it.next());
Iterators
implementation
◦ Etc…
Iterators
for(Worker w : hs)
System.out.println(w);
Iterator<Worker> it=hs.iterator();
while(it.hasNext())
System.out.println(it.next());
Iterator<String> it=hm.keySet().iterator();
while(it.hasNext()){
String k=it.next();
System.out.println(k+","+hm.get(k));
Moshe
Entry:
key
}
value Moshe
System.out.println(k+","+hm.get(k)); 3000
for(Entry<String,Worker> e : hm.entrySet())
System.out.println(e.getKey()+","+e.getValue());
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
49
NEW IN JAVA 8
ForEach
iterator(): Iterator<T>
spliterator(): Spliterator<T>
Collection<E>
public void accept(Integer i) { action.accept(t);
System.out.println(i);
} List<E> Set<E>
};
list.forEach(action);
And many more interfaces & classes…
list.forEach(i->System.out.println(i));
list.forEach(System.out::println);
java.util.function.*
for(Entry<String,Point> e : points.entrySet()){
System.out.println(e.getKey()+","+e.getValue());
points.forEach((K,V)->System.out.println(K+","+V));
points.keySet().forEach(K->System.out.println(K));
points.values().forEach(V->System.out.println(V));
RemoveIf
for(Double d : list)
if(d>15)
list.remove(d);
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
RemoveIf
for(Double d : list)
if(d>15)
toBeDeleted.add(d);
list.removeAll(toBeDeleted);
RemoveIf
list.removeIf(d-> d>15);
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
16
Exception Handling
◦ Divide by zero
◦ Etc.
19
Exception Handling
Normal error handling (in C) would return an error code (eg. –1)
int func(){
//...
This is simple, and sometimes effective method, but:
if(y==0)
18
Throwing Exceptions
String email;
if(!email.contains("@"))
this.email=email;
//...
}
Handling Exceptions
Or throw it on…
PersonalDetails pd;
//...
String email="abc.gmail.com";
pd.setEmail(email);
Handling Exceptions
//...
String email="abc.gmail.com";
try {
pd.setEmail(email);
} catch (Exception e) {
// this is called
e.printStackTrace();
}
at course.java.test.Person.fillDetailsForm(Person.java:10)
course.java.test.Person.main(Person.java:19)
at
Finally block
String email="abc.gmail.com";
try {
pd.setEmail(email);
System.out.println("catching...");
} finally{
System.out.println("safe exit");
} o
17
To
◦ RuntimeException
◦ IOException
◦ Not generally caused by programmer error and generally relating to I/O or network errors
Throwable
Exception Error
StackOverflowError,
FileNotFoundException, NullPointerException, …
UnknownHostException, ArrayIndexOutOfBoundException,
… …
- are checked by the compiler to potentially occur - cannot be checked by the compiler to potentially occur
- you have to handle them in your code - you don’t have to handle them in your code
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
11
15
◦ Spreadsheets
◦ Word processing
◦ Etc
14
Data Streams
◦ localized characters
◦ and objects
13
Byte Streams
InputStream
FileInputStream in = null;
out=new FileOutputStream("myFile.dat");
out.write("Hello World!".getBytes());
myFile.dat:
out.close(); Hello World!
in=new FileInputStream("myFile.dat");
int c;
while((c=in.read()) != -1)
System.out.print(c+",");
104,101,108,108,111,32,87,111,114,108,100,33,
in.close();
12
Important notes
Character Streams
◦ close()
Reader
no
FileReader in = null;
out=new FileWriter("myFile.dat");
in=new FileReader("myFile.dat");
int c;
while((c=in.read()) != -1)
System.out.print(c+","); 104,101,108,108,111,32,87,111,114,108,100,33,
in.close();
FileReader holds the character value in the last 16 bits of the int
FileInputStream holds the character value in the last 8 bits of the int
FileInputStream: FileReader:
characters!
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
23
Line-Oriented I/O
of “End Line”
Buffered Streams
Until now we learned that each read and write request is handled
Very expensive…
Without a buffer…
FileInputStream in=
new FileInputStream("myfile.txt");
int c;
while((c=in.read())!=-1){
With a buffer…
Read Block
Source code
BufferedInputStream in=
new BufferedInputStream(
new FileInputStream("myfile.txt"));
int c;
while((c=in.read())!=-1){
//..
With a buffer…
Read Block
Source code
BufferedInputStream in=
new BufferedInputStream(
new FileInputStream("myfile.txt"));
int c;
while((c=in.read())!=-1){
//..
String line;
writer.println(line);
reader.close();
writer.close();
If you want to flush content of the buffer just use the “flush()”
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
33
Reader
{abstract}
FileReader
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
36
7.5 Scanner
Scanning
Scanning
The resulting tokens may then be converted into values of different types
It is like an iterator!!!
Scanner example
Scanner myScaner=null;
myScaner=new Scanner(
new BufferedReader(
new FileReader("in.txt")));
while(myScaner.hasNext()){
System.out.println(myScaner.next());
Scanner example
double sum=0;
while(s.hasNextDouble())
sum+=s.nextDouble();
s.close();
System.out.println(sum);
1032778.74159
Change Delimiters
useDelimiter(String pattern)
Output:
s.useDelimiter(" fish ");
System.out.println(s.nextInt()); 2
System.out.println(s.nextInt());
red
blue
System.out.println(s.next());
System.out.println(s.next());
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
43
By default,
Standard streams
Wrapping System.in
BufferedReader:
new InputStreamReader(System.in));
Javadoc:
new InputStreamReader(System.in));
Reader InputStream
{abstract} {abstract}
InputStreamReader
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
49
Object Streams
objects
Object Streams
int x,y;
this.x=x;
this.y=y;
return "("+x+","+y+")";
Point p1,p2;
this.p1=p1;
this.p2=p2;
System.out.println(a);
new FileOutputStream("out.txt"));
out.writeObject(a);
new FileInputStream("out.txt"));
System.out.println(b);
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
BASIC API…
CLIENT SIDE
Example
IP:127.0.0.1
TCP/IP
Server port: 6400
Internet
Client
Let’s build a method that gets the user’s input and sends it somewhere
try {
String line;
while(!(line=in.readLine()).equals(exitStr)){
out.println(line);
out.flush();
public void start(String ip, int port){
try {
System.out.println("connected to server");
InputStreamReader(theServer.getInputStream()));
readInputsAndSend(userInput,outToServer,"exit");
readInputsAndSend(serverInput,outToScreen,"bye");
userInput.close();
client.start(ip, port);
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
7
BASIC API…
SERVER SIDE
InputStream inFromClient=aClient.getInputStream();
OutputStream outToClient=aClient.getOutputStream();
Loop this
// interact (read & write) with the client according to protocol Thread
and be this
inFromClient.close(); We want to delegate this
able to outToClient.close();
stop aClient.close();
server.close();
}catch (SocketTimeoutException e) {/*...*/}
this.ch=ch;
stop=false;
server.setSoTimeout(1000);
while(!stop){
try{
ch.handleClient(aClient.getInputStream(), aClient.getOutputStream());
aClient.getInputStream().close();
aClient.getOutputStream().close();
aClient.close();
}catch(SocketTimeoutException e) {/*...*/}
server.close();
}
runServer();
}
stop=true;
// in main()
new Thread(()->runServer()).start();
stop=true;
// in main()
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
14
NEW IN JAVA 8
Each filter manipulates the data stream and passes it on to the next filter
Example:
File
reader Decrypt
Filter Unzip
Filter Tokenizer
Object
reader Object
list
16
Stream
Possible sources
Filter
for(int i=0;i<100;i++)
operation
data.stream().filter(p->p.getX()>0).forEach(System.out::println);
Stream
INTERMEDIATE TERMINAL
distinct()
count()
map() forEach()
limit() reduce()
toArray()
peek()
findAny() , findFirst()
Map-Reduce Example
Map-Reduce Example
String line;
errors.add(line);
in.close();
errors=Files.lines(Paths.get(fileName))
.filter(s->s.startsWith("ERROR:"))
.limit(10)
.collect(Collectors.toList());
String line;
errors.add(line);
in.close();
Stream<String> s=Files.lines(Paths.get(fileName))
errors=s.filter(s->s.startsWith("ERROR:"))
.limit(10)
.collect(Collectors.toList());
s.close();
groupinBy https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
.filter(e->e.name.startsWith("T")) 18:
.collect(Collectors.groupingBy(e->e.age)); Tzipi
22:
EmpByAge.forEach((age,emps)->{ Tal
System.out.println(age+":"); Tomer
emps.forEach(e->System.out.println("\t"+e.name));
});
Parallel Streams
fork-join pool
.filter(e-> e.getClass().equals(Manager.class))
.map(Employee::getSalary)
.reduce(0, (x,y)->(x+y));
Stream 30 33 25 19 20 35 21 22
0 + 0 +
30 + 20 +
63 + 55 +
88 + 76 +
107 + 98
205 …
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
LI oJe vvaa
I Love Java
- A state represents the current string - A state may represent the position of the mouse
- The cost to switch two letters can - The cost to move diagonally can be 15
be derived from their distance
done
5
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
6
◦ In different projects
Where to start?
◦ Domain Specific - specific to a certain domain e.g., the cost to move the mouse
<<algorithm>> <<problem>>
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
10
10 20
5
B C
10 10
10
100
Goal
Since each node represents a “state” of the problem, we can create a State class
Inside, we can use whatever types that can describe states generally
@Override
// ...
12
Since each node represents a “state” of the problem, we can create a State class
Inside, we can use whatever types that can describe states generally
Example of Use:
} a = new State("A");
b = new State("B");
goal=new State("B");
} // true
// ...
13
Who should calculate the cost to move from one state to another??
14
State
String state
s1.setState(state);
State
String state
EightPuzzleState
int[][] state
Domain specific
Domain independent
T state;
this.state=state;
...
}
do
ii. add(s,OPEN)
done
18
Given a state, what are the possible states we can get to?
} “ 86547231”
“8465 7231”
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
20
done
ii. Otherwise, adjust its priority in OPEN
Algorithm
<<Searchable>>
search(Searchable s)
alg.search(new MazeDomain());
alg.search(new WordDomain());
◦ I.e., we can replace the searching algorithm without changing the system’s code
23
The “client” is another programmer, that may use the searching algorithms
<<Searcher>>
Solution sol=searcher.search( );
int n = searcher.getNumberOfNodesEvaluated();
implements
// ...
}
Examples:
24
Let’s assume that all searching algorithms have a priority queue of states
<<Searcher>>
It will be wasteful to implement it over and over again with each algorithm…
25
Let’s assume that all searching algorithms have a priority queue of states
<<Searcher>>
It will be wasteful to implement it over and over again with each algorithm…
{abstract}
protected PriorityQueue<State> openList;
public CommonSearcher() {
openList=new PriorityQueue<State>();
BFS Astar HillClimbing
evaluatedNodes=0;
@Override
public abstract Solution search(Searchable s);
evaluatedNodes++;
return evaluatedNodes;
return openList.poll();
}
}
26
do
done
27
addToOpenList(s.getInitialState());
while(openList.size()>0){
closedSet.add(n);
if(s.isGoalState(n))
state.setCameFrom(n);
addToOpenList(state);
} else{
//...
28
Summary
◦ Make sure to receive the abstract problem type via dependency injection
Extend these abstract classes to define a specific code for a specific algorithm
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
10. UML
◦ Structure diagrams
◦ Behavior diagrams
UML 2.5
Structure Behavior
Class Diagram
Class Name
Attributes
Operations
Singular
Uppercase Maze
Attributes
Operations
Maze
name
entry, exit
data
isSolved
Operations
Maze
data: Integer[][]
isSolved: Boolean
Operations
Maze
data: Integer[][]
isSolved: Boolean
getName
getEntrey
setSolved
possibleMoves
formatMazeData
toString
Maze
data: Integer[][]
isSolved: Boolean
getName ()
getEntrey ()
setSolved (Boolean)
possibleMoves (Position)
formatMazeData ()
toString ()
Maze
data: Integer[][]
isSolved: Boolean
getEntrey () : Position
setSolved (Boolean)
formatMazeData () : String
toString ()
Maze
- data: Integer[][]
- isSolved: Boolean
+ Public
/ Derived
- formatMazeData () : String
~ Package + toString ()
Maze
- data: Integer[][]
- isSolved: Boolean
+ getEntrey () : Position
+ setSolved (Boolean)
This is a note
+ possibleMoves (Position) : Position[]
- formatMazeData () : String
+ toString ()
MazeGenerator
creates Maze
generate(): Maze
Composition Association
Person
Heart Cellphone
heart: Heart
Person
Cellphone
heart: Heart
Composition
Aggregation
<<Searcher>>
search(): Solution
CommonSearcher
# closedList: List
# openList: List
Astar BFS
Object Diagram
Example
Class diagram:
1..*
name = “Bob”
name = “Alice”
age = 34
employees={charlie}
charlie : Architect
name = “Charlie”
age = 25
Package Diagram
Package diagrams
model
Astar Snake …
BFS …
Composite Structure
Diagram
Aircraft
Wing[2]
Cockpit Aileron[2]
Tail
Pedals
RPM gauge Elevator[2]
Propeller
Rudder
Deployment Diagram
Deployment Diagram
◦ Device Nodes
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
29
UML 2.5
Behavior
Activity Diagram
Interaction Diagram
Activity Diagram
Invalid request
3D
2D
Maze 2D
Connect 2D
layers
Idle
generate(…)
In progress Complete
exit() pause()
resume() cancel()
Done Suspended
Canceled
cancel()
Sequence Diagrams
Purchase Items
Customer
Actor: Customer
Scenario:
checkout()
6. System calculates the total sum for payment
itemTotal
calculateDisscount()
finalizeSale()
total
a Payment
submitPayment()
createPayment()
results
results
X
Timing Diagram
http://www.uml-diagrams.org/
http://www.altova.com/umodel/interaction-diagrams.html
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
1
Introduction
Introduction
Introduction
oCreational Patterns
oStructural Patterns
oBehavioral Patterns
◦ identify common communication patterns between objects
oConcurrency Patterns
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
6
Files
תקשורת Predicat
doTask()
implements
• It should stay a pure sorter…
{abstract}
implements
BubbleSorter
obsorble
builder flyweight
mo
pl
um
me
mi
observable
proxy observable
proxy
Class adapter
<<Task>> • The BubbleSorter stays a pure sorter…
<<Sorter>> doTask()
• BubbleSorterTask is a Task
implements • doTask calls the inherited sort method
CommonSorter
{abstract} new TaskManager().runInBackground(
new BubbleSorterTask());
implements
mySorter
<<Sorter>> SorterTask void doTask(){ mySorter.sort(workers); }
implements
CommonSorter
{abstract}
• One adapter to every type of Sorter!
• Our solution is in a higher level
• So it applies to all lower levels!
14
Bridge Design Pattern
DR. ELIAHU KHALASTCHI
Problem:
Abstraction: House
Abstraction: BigHouse
HouseImp
House paintDoor()
paint() paintWindow()
paintRoof()
20
Composite Design Pattern
DR. ELIAHU KHALASTCHI
The Composite Design Pattern
oCreates a “Tree”
charlie : Architect
name = “Charlie”
age = 25
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
25
Decorator Design Pattern
DR. ELIAHU KHALASTCHI
Problem:
TextView
1..* i
<<J>> i <<I>>
32
Façade
DR. ELIAHU KHALASTCHI
The Façade Design Pattern
o A client can be separated from a layer of code with the use of a façade
o A client can command a layer of code to do something
oThe client does not have to know about particulars in the layer
Façade
<<layer’s interface>>
Data
Base
Low Coupling / High Cohesion
oCoupling: the level of dependencies between objects
oDecoupling: the process of reducing these dependencies
oCohesion: how focused is a class around a single responsibility
oWe want high cohesion & low coupling
Façade
Façade Façade
36
Flyweight Design Pattern
DR. ELIAHU KHALASTCHI
Problem:
o How can we minimize the number of objects?
s s s s
r v v Character
r t s a p
col, row : int
r s s
paint()
s s s s s s
s f
Tank
r s p p f
Robot
r s p p
Soldier
Airplane
A solution
oA state becomes a parameter
s s s s Character
o row, col parameters of paint() r v v
r t s a p paint(row,col)
r s s
o Each type appears as one object
s s s s s s Tank
s f
Robot
o A lot of references r s p p f
◦ instead of a lot of objects r s p p Soldier
Airplane
41
Proxy Design Pattern
DR. ELIAHU KHALASTCHI
Proxy Design Pattern
o Governs the access for the real subject
o Remote proxy
◦ Applies caching
o Virtual proxy
◦ Create “expensive” objects by demand
o Protection proxy
◦ Manages access
o Smart reference
◦ Count references
◦ Manage memory
◦ Etc.
Exercise
1. Why use a façade?
2. Which design pattern separates abstractions from implementations?
3. What are the advantages and drawbacks of Decorator?
4. Does Composite patterns allows the creation of a graph?
5. Which design pattern allows us to manage cache?
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
45
Creational Patterns
DR. ELIAHU KHALASTCHI
Factory Design Pattern
Factory Pattern – the problem
o The Application class knows when it is required to create a Document
o It does not know which type of Document should be created
Factory Pattern – the solution
o A concrete Application class creates a concrete Document
◦ MSword creates a wordDocument
◦ MSexcel creates an excelDocument
◦ …
Factory Pattern – the solution
o Generally:
Factory Design Pattern
<<Creator>> Product
Product create()
ProductACreator ProductA
Product create()
ProductBCreator ProductB
Product create()
ProductCCreator ProductC
Product create()
Quiz…
o Let’s say we have n types of workers Worker
Factory Pattern }
private class AdminCreator implements Creator{
public Worker create() {
o First, we implement the interface and
return new Admin();
the classes inside the factory:
}
}
private class TACreator implements Creator{
public Worker create() {
return new TA();
o For each type of Worker, we create
}
a Creator class
}
private class LecturerCreator implements Creator{
public Worker create() {
return new Lecturer();
}
}
...
Factory Pattern
HashMap<String,Creator> workersCreators;
oNext, we create a HashMap!
public WorkerFactory() {
oString Creator
workersCreators=new HashMap<String, Creator>();
oThe key is exactly the user’s parameter workersCreators.put("admin", new AdminCreator());
workersCreators.put("ta", new TACreator());
oThe value is a creator workersCreators.put("lecturer",new LecturerCreator());
oWe instantiate each class once, O(n) mem’ // notice, takes O(n) memory
}
}
Factory Pattern HashMap<String,Creator> workersCreators;
public WorkerFactory() {
oNext, we create a HashMap! workersCreators=new HashMap<String, Creator>();
} return null;
exit
}
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
57
Abstract Factory Design Pattern
DR. ELIAHU KHALASTCHI
Abstract Factory Pattern
o Provides a way to encapsulate a group of individual factories
o that have a common theme
o without specifying their concrete classes
Abstract Factory Pattern - Example
oThe star wars armory and plain armory are interchangeable
oEach can return a sword and a shield
◦ The star wars armory returns a light saber and a deflector shield
◦ The plain armory returns a plain sword and a plain shield
<<Armory>> Sword
+ createSword() : Sword
+ createShield() : Shield PlainSword Lightsaber
62
Prototype Design Pattern
DR. ELIAHU KHALASTCHI
Prototype Pattern – the problem
oWhat do you add?
class ShapesHolder{
ArrayList<Shape> list;
public void addAcopy(Shape s){
list.add(new ???);
}
}
Prototype Pattern
o Each concrete class implements its own close() method
class ShapesHolder{
ArrayList<Shape> list;
public void addAcopy(Shape s){
list.add(s.clone());
}
}
Prototype Pattern – consequences
o Advantages
◦ Independence of concrete types
◦ Quick – we do not have to query the type
o Disadvantages
◦ clone() cannot have (many) parameters
◦ Setters have to be used after the cloning
◦ Shallow vs. deep copy
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
67
Builder Design Pattern
DR. ELIAHU KHALASTCHI
Builder Design Pattern
o The intent is to separate the construction of a complex object
o from its representation
o The same construction process can create different representations
Builder Design Pattern - problem
LevelDirector
+ construct()
createCharacter(new Position(d[0].x,d[0].y));
MarioLevel
Random r=new Random();
for(int i=0;i<100;i++)
createEnemy(new Position(r.nextInt(100), r.nextInt(100)));
AladdinLevel
Bad solution…
LevelDirector BossLevelDirector
# createPlatform(:Position,:Length) # createPlatform(:Position,:Length)
# createCharacter(:Position) # createCharacter(:Position)
# createEnemy(:Position) # createEnemy(:Position)
+ construct()
Level + construct()
createCharacter(new Position(d[0].x,d[0].y));
MarioLevel
Random r=new Random();
for(int i=0;i<100;i++)
createEnemy(new Position(r.nextInt(100), r.nextInt(100)));
AladdinLevel
Builder Design Pattern - Solution
LevelDirector <<LevelBuilder>>
+ construct(builder :LevelBuilder) + createPlatform(:Position,:Length)
+ createCharacter(:Position)
+ createEnemy(:Position)
for(int i=0;i<10;i++) Level + getLevel() : Level
builder.createPlatform(new Position(d[i].x,d[i].y),d[i].l);
builder.createCharacter(new Position(d[0].x,d[0].y));
MarioLevel MarioLevelBuilder
Random r=new Random();
for(int i=0;i<100;i++)
builder.createEnemy(new Position(r.nextInt(100), r.nextInt(100)));
AladdinLevel AladdinLevelBuilder
Level level = builder.getLevel();
Builder Design Pattern - Extended
<<LevelDirector>> <<LevelBuilder>>
+ construct(builder :LevelBuilder) + createPlatform(:Position,:Length)
+ createCharacter(:Position)
+ createEnemy(:Position)
Level + getLevel() : Level
NoviceLevelDirector
MarioLevel MarioLevelBuilder
ExpertLevelDirector
AladdinLevel AladdinLevelBuilder
MasterLevelDirector
BossLevelDirector
Singleton Design Pattern
Exercise…
1. What is the difference between Builder, Factory, and Abstract Factory?
2. Think of 2 ways to avoid creating N classes in Factory.
3. Create an activity diagram for the Singleton Object.
4. How Builder is connected to immutable classes? Fluent programming?
1. Code example
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
78
Builder Pattern Example
DR. ELIAHU KHALASTCHI
Builder Pattern with IOC - Example
// Java example
public class Robot {
// inside Robot class
public static class RobotBuilder{
final String name; // required
final String name;
final int id; // required
final int id;
final double mass;
double mass;
final boolean flyable;
boolean flyable;
final boolean autonomous;
boolean autonomous;
private Robot(RobotBuilder rb){
public RobotBuilder(String name, int id) {
name=rb.name;
this.name=name;
id=rb.id;
this.id=id;
mass=rb.mass;
}
flyable=rb.flyable;
autonomous=rb.autonomous;
}
80
Builder Pattern with IOC - Example
// inside Robot class
public static class RobotBuilder{
final String name;
final int id;
double mass;
boolean flyable;
boolean autonomous;
81
Builder Pattern with IOC - Example
public RobotBuilder setMass(double mass){
// inside Robot class this.mass=mass;
public static class RobotBuilder{ return this;
final String name; }
final int id; public RobotBuilder setFlyable(boolean flyable){
double mass; this.flyable=flyable;
boolean flyable; return this;
boolean autonomous; }
public RobotBuilder setAutonmous(boolean automous){
public RobotBuilder(String name, int id) { this.autonomous=automous;
this.name=name; return this;
this.id=id; }
}
public Robot build(){
return new Robot(this);
}
82
Builder Pattern with IOC - Example
83
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
84
Behavioral Patterns
DR. ELIAHU KHALASTCHI
Command Pattern
Command Pattern
oEvery request is served in a command object
oCommands can inherit other commands
oCommand objects can be put into a queue, manage a log, support “undo” etc.
Invoker
oExample:
document
Receiver
Specific Command
Other invokers can invoke the same specific command; the command code appears only once
Command Pattern
oEvery request is served in a command object
oCommands can inherit other commands
oCommand objects can be put into a queue, manage a log, support “undo” etc.
oExample: Composite structure!
Command Pattern
Example of a general Controller mechanism
oThe Controller is a singleton and an observer
oUpon an update, a key is used to retrieve or create the Command object
oExisting Command objects are stored in a hash table (flyweight pattern)
oNew Command objects are created by a Command-Pool (builder pattern)
oThe Command object is inserted to a priority queue
oA different thread polls commands from the queue, if it is not empty
◦ And execute each Command in a different thread via a Thread Pool
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
91
Interpreter Pattern
DR. ELIAHU KHALASTCHI
Interpreter Pattern
oComposite structure
oThe behavior of interpret() is changed
oCan define a grammar
Interpreter Pattern Example
11*a+5-b/3
-
+ /
AbstractTreeNode
AbstractTreeNode
* 5 b 3
11 a
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
95
Iterator Pattern
DR. ELIAHU KHALASTCHI
Iterator Pattern
oEnables access to items of a complex object
owithout exposing its inner structure
oEach container should return its own type of iterator
oShould consider:
◦ Who defines the iteration alg’?
◦ How robust is the iterator?
◦ E.g., when deleting items
Iterator Pattern Example
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
99
Observer Pattern
DR. ELIAHU KHALASTCHI
Observer Pattern
C++ Example
102
Observer & Observable
class Observable; class Observable{
class Observer{ list<Observer*> observers;
public: public:
virtual void update(Observable& o) = 0; void addObserver(Observer& o){
}; observers.push_back(&o);
}
void notify(){
list<Observer*>::iterator it = observers.begin();
while (it != observers.end()){
(*it)->update(*this);
it++;
}
}
};
103
Usage:
class A : public Observable{ class B :public Observer{
int x; // our observable data A* a;
public: public:
void set(int x){ B(A* a){
this->x = x; this->a = a;
notify(); a->addObserver(*this);
} }
int get(){ return x; } void update(Observable& o){
}; int x = a->get();
cout << "b is updated" << endl;
int main(){ }
A a; };
B b(&a);
a.set(5);// b is updated
return 0;
}
104
C# Example
OBSERVER PAT TERN
Delegate variable vs. Event variable
o public void f(){…};
o public void g(){…};
o public delegate void myFunc();
Observable theObservable
public void delegate update(Object sender, EventArgs args); Observer
public event update notify;
theObservable.notify +=
// when it is needed to notify all observers delegate(Object sender, EventArgs e){
notify(this, theEventArgs); // do something about the notification
}
An Alarm Clock Example
class AlarmClock {
public Boolean stop;
customEvent(time);
Thread.Sleep(1000);
}
}
).Start();
}
}
108
An Alarm Clock Example
o Now we can use the event’s += operator to assign as many delegates as we wish
o The -= operator removes delegates from the event
static void Main(string[] args) {
AlarmClock ac = new AlarmClock();
ac.start();
Thread.Sleep(3*60*1000);
ac.stop = true;
Console.ReadKey();
}
109
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
110
State Pattern
DR. ELIAHU KHALASTCHI
State Pattern
oThe object changes its behavior when its state is changed
oAll of the sate related behaviors are bound to the same class
oEasy to add new behaviors and maintain existing ones
Health
+ move()
Healthy Faulty
+ move() + move()
בית הספר למדעי המחשב
מרצה :ד"ר אליהו חלסצ'י
114
Template Vs. Strategy
DR. ELIAHU KHALASTCHI
Template Method
Change the behavior of a (template) method by calling abstract methods
sort(…)
compare(…): int
compare(t1:T,t2:T): int
T=Worker