Professional Documents
Culture Documents
programiranje
Frameworks, kontrola pristupa,
postojani objekti, kompleksnost
sustava
2
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
void area() {
cout << "Parent class area :" << endl;
}
};
int main() {
Rectangle shape[4];
Rectangle r1(10, 7);
Rectangle r2(10, 10);
shape[0] = r1;
shape[1] = r2;
shape[0].area();
shape[1].area();
shape[0].sayIsSquare();
shape[1].sayIsSquare();
}
int main() {
Što ako promijenimo u Shape
Shape shape[4];
Rectangle r1(10, 7);
Rectangle r2(10, 10);
shape[0] = r1;
shape[1] = r2;
shape[0].area();
shape[1].area(); ERROR: ne postoji sayIsSquare
shape[0].sayIsSquare();
shape[1].sayIsSquare();
}
ect slicing
Obj
Objektno orijentirano programiranje
6
...
void virtual area() {
cout << "Parent class area :" << endl;
}
...
int main() {
Shape * shape[4];
Rectangle r1(10, 7);
Rectangle r2(10, 10);
shape[0] = &r1;
shape[1] = &r2;
(*shape[0]).area();
(*shape[1]).area();
}
polymorphism
run time
Objektno orijentirano programiranje
7
S.O.L.I.D.
S.O.L.I.D
• Single-responsibility Principle
• Open-closed Principle
• Liskov substitution principle
• Interface segregation principle
• Dependency Inversion principle
https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
S.O.L.I.D
Single-responsibility Principle
class Circle {
public $radius;
class Square {
public $length;
class AreaCalculator {
protected $shapes;
public function __construct($shapes = array()) {
$this->shapes = $shapes;
}
public function sum() {
// logic to sum the areas
}
public function output() {
return implode('', array(
"",
"Sum of the areas of provided shapes: ",
$this->sum(),
""
));
}
}
$shapes = array(
new Circle(2), Problem! AreaCalculator se ne bi
trebala baviti ispisom podataka.
new Square(5),
new Square(6)
);
$areas = new
AreaCalculator($shapes);
echo $areas->output();
$shapes = array(
new Circle(2),
new Square(5),
new Square(6)
);
S.O.L.I.D
Open-closed principle
return array_sum($area);
}
interface ShapeInterface {
public function area();
}
S.O.L.I.D
Liskov substitution principle
class SumCalculatorOutputter {
protected $calculator;
public function __constructor(AreaCalculator
$calculator) {
$this->calculator = $calculator;
}
public function JSON() {
$data = array(
'sum' => $this->calculator->sum();
);
return json_encode($data);
} Pozivamo sum()
public function HTML() {
return implode('', array(
'',
'Sum of the areas of provided shapes: ',
$this->calculator->sum(),
''
));
} Program se ne buni, ali neće
} funkcionirati.
class Email(Notification):
def notify(self, message, email):
print(f'Send {message} to {email}')
class SMS(Notification):
def notify(self, message, phone):
print(f'Send {message} to {phone}') notify() od Emaila i notify() od
SMS nemaju isti potpis.
if __name__ == '__main__’:
notification = SMS()
notification.notify('Hello', 'john@test.com')
class Contact:
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
class NotificationManager:
def __init__(self, notification, contact): send() provjerava o kojoj klasi je
self.contact = contact riječ. Ovo nije dobro.
self.notification = notification
if __name__ == '__main__’:
contact = Contact('John Doe', 'john@test.com', '(408)-888-9999’)
notification_manager = NotificationManager(SMS(), contact)
notification_manager.send('Hello John')
if __name__ == '__main__’:
class Email(Notification): contact = Contact('John Doe', 'john@test.com',
def __init__(self, email): '(408)-888-9999')
self.email = email
sms_notification = SMS(contact.phone)
def notify(self, message): email_notification = Email(contact.email)
print(f'Send "{message}" to {self.email}')
notification_manager =
NotificationManager(sms_notification)
class SMS(Notification): notification_manager.send('Hello John')
def __init__(self, phone):
self.phone = phone notification_manager.notification =
email_notification
def notify(self, message): notification_manager.send('Hi John')
print(f'Send "{message}" to {self.phone}')
class Contact:
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
Dodali smo
Contact klasu
S.O.L.I.D
Interface segregation principle
interface ShapeInterface {
public function area();
}
interface SolidShapeInterface {
public function volume();
}
interface ManageShapeInterface{
public function calculate();
}
S.O.L.I.D
Dependency Inversion principle
class PasswordReminder {
private $dbConnection; High level modul
interface DBConnectionInterface {
public function connect();
}
Frameworks
Framework
• Ponovno korištenje koda
– nije isključivo za OO programiranje
• Framework i standardizacija – jednoznačnost korištenja kako
za programera i tako i za krajnjeg korisnika programa
• Npr. stvaranje prozora u Windowsima je standardizirano sa
istim funkcionalnostima
• Kod korišten u frameworku je već testiran
• Postoje frameworks za različite primjene (npr. word
processing – definirane su standardne radnje kao copy-paste,
otvaranje, spremanje, pretraga, …)
• Učenje i iznova programiranje već napravljenih stvari nije
isplativo
Objektno orijentirano programiranje
36
Framework
• Očito pitanje je – ako trebamo koristiti dijalog-box koji
nam pruža framework – kako ga upotrijebiti?
• Pravila korištenja se obično nalaze u dokumentaciji
framework-a
• Osoba koja piše klasu/klase je zadužena i za pisanje
dokumentacije kako koristiti javni interfejs klase
• Veće tvrtke obično napišu i koriste svoj framework
specifičan za njihove aplikacije
• Postoje i general-purpose frameworks i libraries
• Postoje različite definicije frameworka
Framework
• Po nekim definicijama framework predstavlja veću
cjelinu/generalniji pojam od biblioteke, može biti i skup
biblioteka
• Framework za razliku od biblioteke upravlja tokom
programa – inversion of control – tok programa ne diktira
korisnik već framework
Inversion of Control
d b y t h e a p p li ca tion
fa ce s w e r e c o n trolle
"Early user inte r o f c o m m a n d s li ke
u ld h a v e a s e q u ence
program. You wo p r o g r a m w o u ld drive
e nt e r a d d r e s s " ; your
"Enter name", " t o e a c h o n e . W ith
p ic k u p a r e s p o nse
the prompts and n b a s e d) U Is t h e U I f r a m e work
e v e n s cr e e e ad
graphical (or lo o p a n d you r p r o g r a m in st
is m a in
would contain th r s fo r the v a r io u s fie ld s o n the
e n t h a n d le e d,
provided ev l o f t h e pr o g r a m w a s in v e r t
c o n t r o
screen. The main to t h e f r a m e w o rk."
ove d a w a y fr o m you
m
Inversion of Control
print "enter your name"
read name
print "enter your address"
read address
etc...
store in database
o više od toga
ak, IoC je mal
Ip
Objektno orijentirano programiranje
40
Inversion of Control
public static void main(String[] args) {
while (true) {
BufferedReader userInputReader = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Please enter some text: ");
try {
System.out.println(userInputReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
S.O.L.I.D.
S - Single-responsiblity principle
O - Open-closed principle
L - Liskov substitution principle
I - Interface segregation principle
D - Dependency Inversion Principle
https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
S.O.L.I.D.
S - Single-responsiblity principle
O - Open-closed principle
L - Liskov substitution principle
I - Interface segregation principle
D - Dependency Inversion Principle
Contracts
• Mehanizam koji zahtjeva od developera da se pridržava
specifikacija API-ja ili frameworka
• To znači da se pridržava načina imenovanja metoda
(standard imenovanja) i korištenja putem kojeg se
osigurava dobra praksa pisanja koda
• Standard nema smisla ako ga ljudi ne koriste što rezultira
nerazumljivim kodom
• U Javi i .NET jezicima pridržavanje se osigurava
apstraktnim klasama i interfejsima
class Unrelated {
private:
Base B;
public:
int foo1() { return B.MyPrivateInt;} // Won't compile!
int foo2() { return B.MyProtectedInt;} // Won't compile
int foo3() { return B.MyPublicInt;} // OK
};
j mo još ne ke
Pogleda
imj er e u Jav i
pr
class Person {
private String firstname;
private String lastname;
public Company() {
this.people = new ArrayList<Person>();
}
public void addPerson(String firstname, String lastname) {
Person p = new Person();
p.setFirstname(firstname);
p.setLastname(lastname);
this.people.add(p);
}
public void printPeople() {
for(int i = 0; i < this.people.size(); i++) {
System.out.println(
this.people.get(i).getFirstname() + " " +
this.people.get(i).getLastname());
}
}
}
U Javi
š malo na C++
Vratimo se jo
tojani objekti
Pos
Serijalizacija
• Da bi objekt slali kroz kanal (npr. putem interneta) potrebno ga
je dekonstruirati (razbiti u elementarne podatke, npr. byte
stream), poslati i onda ga ponovno složiti na drugom kraju kanala
– ovaj proces naziva se serijalizacija (eng. serialization)
• Proces samog slanja kroz mrežu zove se „marshaling”
• Serijalizirani objekt se može zapisati u file i poslije opet vratiti u
originalno stanje
• Serijaliziacija i deserijalizacjia trebaju koristiti iste specifikacije
(metodu dekompozicije i kasnije vraćanja u stanje objekta) –
slično kao enkripcijski algoritam
• Java pruža interfejs – Serializable
• .NET jezici pružaju interfejs ISerializable
Serijalizacija u Javi
package Serialization;
import java.util.*;
import java.io.*;
class Osoba implements Serializable{
private String ime;
public Osoba(){
}
public Osoba(String i){
System.out.println(“Konstruktor”);
ime = i;
}
String dohvatiIme() {
return ime;
}
}
Serijalizacija u Javi
public class SpremiOsobu implements Serializable{
public SpremiOsobu(){
Osoba osoba = new Osoba(“Ivo Ivić”);
try{
FileOutputStream fos = new FileOutputStream(“Dat.txt”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(osoba);
oos.flush();
oos.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
Serijalizacija u Javi
U ovom primjeru:
Serijalizacija u Javi
package Serialization;
import java.io.*;
import java.util.*;
public class UcitajOsobu{
public UcitajOsobu(){
try{
FileInputStream fis = new FileInputStream(“Dat.txt”);
ObjectInputStream ois = new ObjectInputStream(fis);
Osoba osoba = (Osoba)ois.readObject();
System.out.print(“Učitano ime osobe: “);
System.out.println(osoba.dohvatiIme());
ois.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
ZADATAK
• Serijalizacija u C#
KRAJ