1 software design uml basics template class example (chain) stl vector class operator overloading...
TRANSCRIPT
1
Software Design UML Basics Template Class Example (Chain) STL Vector Class Operator Overloading Ray class Example
CSE 30331CSE 30331Lecture 2 – Design & Some ExamplesLecture 2 – Design & Some Examples
2
Software Design Overview State the problem to be solved.
Analyze the problem to extract requirements. Proceed through a series of stages to produce a product
that is reliable and easy to maintain.
3
Software Design Overview
Prior to the standardization of the software development life cycle: Programmers added code to software with little
attention to its integration into the system. Over time systems deteriorated and became so
difficult to update that programmers had to develop new software to replace them.
4
Software Design Stages
Request Analysis Design Implementation Testing Maintenance
5
Software Design Stages
Request Client has problem software might solve Consultant undertakes a feasibility study for the project
Analysis Identifes system requirements Creates a functional specification Lists needs and special requirements
6
Software Design Stages
Design Translates the functional specification into an abstract
model of the system Identifies the components of the system Develops algorithms for implementation
Implementation Uses a programming language Uses the design specification Creates code for all system components
7
Software Design Stages
Testing Unit testing & Integration testing Verification – meets requirements Validation – meets user’s needs Syntax vs. Semantic (logical) errors Black-box vs. White-box testing Test data (inputs in range, out of range, boundary)
Maintenance Periodically update the software to stay current and to
respond to changing needs of the client.
8
UML – Unified Modeling Language
Common representation of program … Design Usage Components
Use Case Diagrams Class Diagrams
9
UML – Use Case Diagrams
Represent from user perspective how program (system) is to be used
ATM example Make deposit Make withdrawal Check account balance Transfer funds between accounts
Make deposit
Make withdrawal
Check Account Balance
Transfer funds between accounts
10
UML – Class Diagrams
Represent attributes and behavior of class Top box shows data members Bottom box shows member functions “+” indicates public “-” indicates private
Account Class Example
accountNumber : integerpin : integeravailableBalance : doubletotalBalance : double
validatePin( ) : booleangetAvailableBalance( ) : doublegetTotalBalance( ) : doublecredit( )debit( )
11
UML – Class Relationships
Diamond indicates composition relationship ATM has-a Screen ATM has-a Keypad ATM has-a CashDispenser ATM has-a DepositSlot
Screen
ATM
Keypad
CashDispenserDepositSlot
1
111
1
1
11
12
UML – System Model
Shows class relationships AND interactions
Screen
ATM
bankDatabase
DepositSlot
1
1
0..1
1
1
11
CashDispenser
WithdrawalExecutes
1
1 1
0..1
Accesses/Modifies account balance through
Authenticates user against
13
Operator Overloading
Operators may be overloaded as either … Member functions
Left operand must be object of this class (rhs + lhs) Friend functions
At least one operand is member of this class Function has access to private parts of class
Free functions Function has no access to private parts of class Class must provide all necessary public methods
14
Operator Overloading Example
Ray class (2-d vectors in Cartesian coords) Data Members
dx & dy – specify direction and magnitude Member Functions
Ray(x,y) – constructor operator+(r) – vector addition operator*(s) – scalar multiplication (r*s)
Friend functions Operator<<(str,r) – insertion into stream Operator>>(str,r) – extraction from stream Operator*(s,r) – scalar multiplication s*r
15
Ray Class#include <iostream>class Ray{ friend Ray operator*(double s, Ray r); friend std::istream& operator>> (std::istream& str, Ray& r); friend std::ostream& operator<< (std::ostream& str, Ray r); public: Ray(const double x=1.0, const double y=0.0); Ray operator*(double s); Ray operator+(Ray r);
private: double dx, dy;};
16
Ray Class Member Functions#include “Ray.h”
Ray::Ray(const double x, const double y): dx(x), dy(y){ }Ray Ray::operator*(double s){ // multiply both components by scalar s Ray result(s*dx, s*dy); return result;}Ray Ray::operator+(Ray r){ // add corresponding components of two rays
Ray result(dx+r.dx, dy+r.dy);return result;
}
17
Ray Class Friend FunctionsRay operator*(double s, Ray r){// multiply both components by scalar s Ray result(s*r.dx, s*r.dy); return result;}std::istream& operator>> (std::istream& str, Ray& r){ //extract two ray components str >> r.dx >> r.dy; return str;}std::ostream& operator<< (std::ostream& str, Ray r){ // insert two ray components separated by a space str << r.dx << “ “ << r.dy; return str;}
18
Ray Class – sample use
// declare Rays and exercize all related operators#include <iostream>#include “Ray.h”using namespace std;int main( ){ Ray r1, r2, result; cout << “Enter two rays x1 y1 x2 y2: “; cin >> r1 >> r2; result = -1.0 * ((r1 + r2) * 4.0); cout << “r1 = “ << r1 << “, r2 = “ << r2 << endl; cout << “-1.0 * ((r1 + r2) * 4.0) = “ << result << endl; return 0;}
19
Template Class Example
Chain class (sequence of items) Data member
STL vector of items Member functions
Chain( ) – creates empty sequence Append (item) – appends item to sequence Total ( ) – traverses sequence and totals it
NOTE: “total” has different meanings depending on what “+” means with respect to the item type Strings are concatenated Rays are added as 2-d vectors in Cartesian coordinates ints are added normally
20
Chain Class
template<class T>
class Chain
{
public:
Chain();
void append(const T& item);
T total();
private:
vector<T> items;
};
21
Chain Class Members
// simple constructor, nothing to dotemplate<class T>Chain<T>::Chain(){ }
// simple append, just use vector push_back to do alltemplate<class T>void Chain<T>::append(const T& item){ items.push_back(item);}
22
Chain Class Members// pretty simple total procedure: handle empty Chain// in some way, then sum, concatenate, or whatever// is appropriate for “+” with respect to items of // type Ttemplate<class T>T Chain<T>::total(){ if (0 == items.size()) return T(); // or throw an emptyChain error
T result(items[0]); // start with value of first item for (int i=1; i<items.size(); i++) result = result + items[i]; // “sum” each other item return result;}
23
Chain of Rays Example#include <iostream>#include “Ray.h”#include “Chain.h”using namespace std;int main( ) { Ray r; Chain<Ray> sequence; cout << “Enter a ray -- x y (\"e\" to end): “; while (cin >> r) { sequence.append(r); cout << “Enter a ray -- x y (\"e\" to end): “; } cout << “TOTAL is : “ << sequence.total() << endl; return 0;}
24
Chain of strings Example#include <iostream>#include <string>#include “Chain.h”using namespace std;int main( ) { string str; Chain<string> sequence; cout << “Enter a name : “; while (getline(cin,str) && (str != “”)) { sequence.append(str); cout << “Enter a name : “; } cout << “TOTAL is : “ << sequence.total() << endl; return 0;}
25
STL Containers
All containers have the following ContType c – create empty container ContType c1(c2) – create copy of container ContType c(beg,end) – initialize with items[beg,end) c.~ContType() – delete elements and free memory c.size() – return number of elements c.empty() – is container empty or not c.max_size() – max number of elements possible
26
STL Containers
All containers have the following c1 == c2 – are containers equal? c1 != c2 – are they not equal c1 < c2 – less than based on lexicographical ordering c1 > c2 – greater than c1 <= c2 – less than or equal c1 >= c2 – greater than or equal c1 = c2 – assigns elements of c2 to c1 c1.swap(c2) – swaps elements of two containers swap(c1,c2) – same as above
27
STL Containers
All containers have the following c.begin() – returns iterator to first element c.end() – returns iterator past last element c.rbegin() – returns reverse iterator for last element c.rend() – returns reverse iterator before first element c.insert(pos,elem) – inserts copy of elem c.erase(beg,end) – removes elements [beg,end) c.clear() – removes all elements c.get_allocator() – returns memory model
28
Vector Container
Vectors also have … vector<T> c – creates empty vector vector<T> c1(c2) – creates copy of vector c2 vector<T> c(n) – creates vector of n elements vector<T> c(n,e) – creates vector of n copies of e vector<T> c(beg,end) – creates vector copying
elements from range [beg,end) c.~vector<T>() – clears elements and frees memory
29
Vector Container
Vectors also have … c.capacity() – returns max elements w/o reallocation c.reserve(n) – enlarges capacity c.assign(n,e) – assigns n copies of e c.assign(beg,end) – assigns elements [beg,end) c.at(idx) – returns element at position idx c[idx] – same as previous c.front() – returns first element c.back() – returns last element
30
Vector Container
Vectors also have … c.insert(pos,n,e) – inserts n copies of e at iterator pos c.insert(pos,beg,end) – inserts at iterator pos the
elements in range [beg,end) c.push_back(e) – appends e to vector c.pop_back() – removes last element from vector c.erase(pos) – removes element at iterator pos c.resize(num) – changes number of elements and fills
with value of default element constructor c.resize(num,e) – changes size and fills with e