Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Метод указ к лабораторным работам ООП 3 семест...doc
Скачиваний:
5
Добавлен:
13.11.2019
Размер:
22.34 Mб
Скачать

2.4 Приклад виконання роботи Задача

Компанія будує двоповерховий офіс і обладнує його ліфтом. Потрібно розробити програмне забезпечення для моделювання роботи цього ліфта, щоб визначити, чи задовольняє він призначенню. Вимоги до ліфта такі: призначений для одного пасажира; переміщується тільки за потребою (для збереження енергії); розпочинає роботу із очікування при зачинених дверях на першому поверху: може змінювати напрям руху — спочатку догори, потім донизу. Ліфт рухається з пасажиром після натискання кнопки ліфта. Для виклику ліфта на поверх пасажир натискає кнопку поверху. Ліфт сигналізує про своє прибуття на поверх лампою та дзвоником. Ліфт рухається при зачинених дверях. Планувальник процесу генерує появу пасажира.

Об’єктно-орієнтоване проектування Зображення класів в uml

ІМ’Я_КЛАСУ

имя_атрибута 1: тип_1 = значение_по_умолчанию_1 имя_атрибута 2: тип_2 = значение_по_умолчанию_2 . . . . . . . . . . . . . . .

имя_операции_1 (список_аргументов_1): тип_результата сигнатура_операции_2 сигнатура_операции_3 . . . . . . . . . . . . . . . .

Рис. 2.4. Діаграма класів

Рис. 2.5. Діаграма об’єктів для ситуації, коли в будівлі нема людей

Ідентифікація атрибутів

Рис. 2.6. Діаграма класів з атрибутами

Структура проекту

Рис. 2.7. Перелік класів проекту

Інтерфейси та реалізації класів програми

// bell.h

// interface of the class Bell

#ifndef BELL_H

#define BELL_H

class Bell {

public:

Bell(); // constructor

~Bell(); // destructor

void ActionBell(); // ring the bell

};

#endif // BELL_H

// bell.cpp

// implementatiin of the class Bell

#include <iostream>

using namespace std;

#include "bell.h"

Bell::Bell() // constructor

{ }

Bell::~Bell() // destructor

{}

void Bell::ActionBell() // ring bell

{ }

// building.h

// Definition for class Building.

#ifndef BUILDING_H

#define BUILDING_H

#include "elevator.h"

#include "floor.h"

#include "clock.h"

#include "scheduler.h"

class Building {

public:

Building(); // constructor

~Building(); // destructor

void RunSimulation( int ); // run //simulation for specified time

private:

Floor floor1; // floor1 object

Floor floor2; // floor2 object

Elevator elevator; //elevator object

Clock clock; // clock object

Scheduler scheduler;// scheduler object

};

#endif // BUILDING_H

// building.cpp

// implementatiin of the class Building.

#include <iostream>

using namespace std;

#include "building.h"

Building::Building() // constructor

: floor1(1 , elevator ),

floor2(2 , elevator ),

elevator( floor1, floor2 ),

scheduler( floor1, floor2 )

{ }

Building::~Building() // destructor

{ }

// control the simulation

void Building::RunSimulation( int totalTime)

{}

// door.h

// Definition for class Door.

#ifndef DOOR_H

#define DOOR_H

//for using as parameters in functions

class Person; // forward declaration

class Floor; // forward declaration

class Elevator; // forward declaration

class Door {

public:

Door(); // constructor

~Door(); // destructor

void OpenDoor(Person*, Person* ,

Floor&, Elevator& );

void closeDoor( Floor& );

private:

bool open; // open or closed

};

#endif // DOOR_H

// door.cpp

// implementatiin of the class Door.

#include <iostream>

using namespace std;

#include "door.h"

#include "person.h"

#include "floor.h"

#include "elevator.h"

Door::Door():open(false) // constructor

{ }

Door::~Door() // destructor

{}

// open the door

void Door::OpenDoor(Person* passengerPtr,

Person* nextPassengerPtr,

Floor &currentFloor,

Elevator &elevator )

{ }

// close the door

void Door::closeDoor(Floor& currentFloor)

{}

// elevator.h

// Definition for class Elevator.

#ifndef ELEVATOR_H

#define ELEVATOR_H

#include "elevatorButton.h"

#include "door.h"

#include "bell.h"

//for using as parameters in functions

class Floor; // forward declaration

class Person; // forward declaration

class Elevator {

public:

Elevator(Floor&, Floor&);//constructor

~Elevator(); // destructor

void SummonElevator( int ); // request to service a floor

void PrepareToLeave( bool ); // prepare to leave

void ProcessTime( int ); // give time to elevator

void PassengerEnters( Person*); // board a passenger

void PassengerExits(); // exit a passenger

ElevatorButton elevatorButton; // note public object

private:

void ProcessPossibleArrival();

void ProcessPossibleDeparture();

void ArriveAtFloor( Floor & );

void Move();

bool moving; // elevator state

int direction; // current direction

int currentFloor; //current location

int arrivalTime; //time to arrive at //a floor

Floor &floor1Ref;// reference to floor1

Floor &floor2Ref;// reference to floor2

Person *passengerPtr; // pointer to //current passenger

Door door; // door object

Bell bell; // bell object

};

#endif // ELEVATOR_H

// elevator.cpp

// implementatiin of the class Elevator.

#include <iostream>

using namespace std;

#include "elevator.h"

#include "person.h"

#include "floor.h"

// constructor

Elevator::Elevator( Floor &firstFloor, Floor &secondFloor )

: elevatorButton( *this )

, moving( false )

, direction( 0 )

, currentFloor(1)

, arrivalTime(0)

, floor1Ref( firstFloor )

, floor2Ref( secondFloor )

, passengerPtr( 0 )

{ }

Elevator::~Elevator() // destructor

{}

// give time to elevator

void Elevator::ProcessTime( int time )

{ }

// when elevator is moving, determine if it should stop

void Elevator::ProcessPossibleArrival()

{}

// determine if elevator should Move

void Elevator::ProcessPossibleDeparture()

{}

// arrive at a particular floor

void Elevator::ArriveAtFloor( Floor& arrivalFloor )

{}

// request service from elevator

void Elevator::SummonElevator( int floor)

{ }

// accept a passenger

void Elevator::PassengerEnters( Person * personPtr )

{}

//notify elevator that passenger is exiting

void Elevator::PassengerExits()

{ }

// prepare to leave a floor

void Elevator::PrepareToLeave( bool leaving)

{}

// go to a particular floor

void Elevator::Move()

{}

// elevatorButton.h

// Definition for class ElevatorButton.

#ifndef ELEVATORBUTTON_H

#define ELEVATORBUTTON_H

#include "button.h"

class Elevator; // forward declaration

class ElevatorButton

{

public:

ElevatorButton(Elevator&);//constructor

~ElevatorButton(); // destructor

void PressButton();// press the button

};

#endif // ELEVATORBUTTON_H

// elevatorButton.cpp:

// implementatiin of the class //ElevatorButton.

#include <iostream>

using namespace std;

#include "elevatorButton.h"

#include "elevator.h"

// constructor

ElevatorButton::ElevatorButton(

Elevator &elevatorHandle )

{ }

// destructor

ElevatorButton::~ElevatorButton()

{ }

// press the button

void ElevatorButton::PressButton()

{}

// floor.h

// Definition for class Floor.

#ifndef FLOOR_H

#define FLOOR_H

#include "floorButton.h"

#include "light.h"

#include "door.h"

class Elevator; // forward declaration

class Person; // forward declaration

class Floor {

public:

Floor(int, Elevator&); // constructor

~Floor(); // destructor

bool IsOccupied(); //true if floor

//occupied

int GetNumber(); // floor's number

// new person coming on floor

void PersonArrives( Person* );

//notify floor that elevator has arrived

Person *elevatorArrived();

//notify floor that elevator is leaving

void ElevatorLeaving();

//notify floor that person is leaving

void PersonBoardingElevator();

//floorButton object

FloorButton floorButton;

private:

int floorNumber; //the floor's number

Elevator& elevatorRef;//pointer to elevator

Person* occupantPtr; // pointer to person on floor

Light light; // light object

};

#endif // FLOOR_H

// floor.cpp

// implementatiin of the class Floor.

#include <iostream>

using namespace std

#include "floor.h"

#include "person.h"

#include "elevator.h"

// constructor

Floor::Floor(int number, Elevator &elevatorHandle)

: floorButton( number, elevatorHandle) , floorNumber( number ) , elevatorRef( elevatorHandle ) , occupantPtr (0) , light(floorNumber==1?"floor1":"floor2")

{}

Floor::~Floor() // destructor

{}

// determine if floor is occupied

bool Floor::IsOccupied()

{ return 0; }

// return this floor's number

int Floor::GetNumber()

{ return floorNumber; }

// pass person to floor

void Floor::PersonArrives( Person* personPtr )

{ }

// notify floor that elevator has arrived

Person *Floor::elevatorArrived()

{ return occupantPtr;}

// tell floor that elevator is leaving

void Floor::ElevatorLeaving()

{ }

// notifies floor that person is leaving

void Floor::PersonBoardingElevator()

{}

// floorButton.h

// Definition for class FloorButton.

#ifndef FLOORBUTTON_H

#define FLOORBUTTON_H

#include "button.h"

class Elevator; // forward declaration

class FloorButton

{

public:

FloorButton(int, Elevator&); // constructor

~FloorButton(); // destructor

void PressButton();//press the button

private:

int floorNumber; //number of the button's floor

};

#endif // FLOORBUTTON_H

// floorButton.cpp

// implementatiin of the class //FloorButton.

#include <iostream>

using namespace std;

#include "floorButton.h"

#include "elevator.h"

// constructor

FloorButton::FloorButton(int number,

Elevator &elevatorHandle )

: floorNumber( number )

{ }

FloorButton::~FloorButton() // destructor

{ }

// press the button

void FloorButton::PressButton()

{}

// clock.h

// Definition for class Clock.

#ifndef CLOCK_H

#define CLOCK_H

class Clock {

public:

Clock(); // constructor

~Clock(); // destructor

void tick(); //increment clock by second

int GetTime();//returns current time

private:

int time; // clock's time

};

#endif // CLOCK_H

// clock.cpp

// implementatiin of the class #include <iostream>

using namespace std;

#include "clock.h"

Clock::Clock(): time( 0 ) // constructor

{ }

Clock::~Clock() // destructor

{ }

void Clock::tick()// increment time by 1

{ }

int Clock::GetTime()//return current time

{ return 0; }

// person.h

// definition of class Person

#ifndef PERSON_H

#define PERSON_H

class Floor; // forward declaration

class Elevator; // forward declaration

class Person {

public:

Person( int ); // constructor

~Person(); // destructor

int GetID(); // returns person's ID

void StepOntoFloor( Floor & );

void EnterElevator(Elevator&, Floor&);

void ExitElevator(Floor&, Elevator& );

private:

int personCount;//number of persons

int ID; //person's unique ID #

int destinationFloor; //destination // floor #

};

#endif // PERSON_H

// person.cpp

// implementatiin of the class Person.

#include <iostream>

using namespace std;

#include "person.h"

#include "floor.h"

#include "elevator.h"

// constructor

Person::Person( int destFloor )

: ID( ++personCount )

, destinationFloor( destFloor )

{}

Person::~Person() // destructor

{}

int Person::GetID()

{ return ID; } // get the ID

// person walks onto a floor

void Person::StepOntoFloor(Floor& floor)

{}

// person enters elevator

void Person::EnterElevator( Elevator& elevator, Floor &floor )

{ }

// person exits elevator

void Person::ExitElevator(Floor &floor, Elevator &elevator)

{}

// scheduler.h

// defintion for class Scheduler

#ifndef SCHEDULER_H

#define SCHEDULER_H

class Floor; // forward declaration

class Scheduler {

public:

// constructor

Scheduler( Floor &, Floor & );

~Scheduler(); // destructor

void ProcessTime(int); // set scheduler's time

private:

// schedule arrival to a floor

void ScheduleTime(Floor & );

// delay arrival to a floor

void DelayTime(Floor & );

// create new person; place on floor

void CreateNewPerson( Floor & );

// handle person arrival on a floor

void HandleArrivals( Floor &, int );

Floor &floor1Ref;

Floor &floor2Ref;

};

#endif // SCHEDULER_H

// scheduler.cpp

// implementatiin of the class Scheduler.

#include <iostream>

using namespace std ;

#include <cstdlib>

#include <ctime>

#include "scheduler.h"

#include "floor.h"

#include "person.h"

// constructor

Scheduler::Scheduler( Floor &firstFloor, Floor &secondFloor )

: floor1Ref( firstFloor )

, floor2Ref( secondFloor )

{}

Scheduler::~Scheduler() // destructor

{ }

// schedule arrival on a floor

void Scheduler::ScheduleTime(Floor &floor)

{}

// reschedule an arrival on a floor

void Scheduler::DelayTime(Floor &floor )

{}

// give time to scheduler

void Scheduler::ProcessTime( int time )

{}

// create new person and place it on specified floor

void Scheduler::CreateNewPerson( Floor &floor)

{}

// handle arrivals for a specified floor

void Scheduler::HandleArrivals( Floor &floor, int time )

{}

// light.h

// Definition for class Light.

#ifndef LIGHT_H

#define LIGHT_H

class Light {

public:

Light(char * ); // constructor

~Light(); // destructor

void TurnOn(); // turns light on

void TurnOff(); // turns light off

private:

bool on; //true if on; false if off

char *name;//which floor the light is on

};

#endif // LIGHT_H

// light.cpp

// implementatiin of the class Light.

#include <iostream>

using namespace std;

using std::endl;

#include "light.h"

Light::Light(char *string ) //constructor

: on( false )

, name( string )

{ }

Light::~Light() // destuctor

{}

void Light::TurnOn() // turn light on

{ }

void Light::TurnOff() // turn light off

{ }

// Driver for the simulation.

#include <iostream>

using namespace std;

#include "building.h"

void main()

{

int duration;//duration of simulation

cout << "Enter run time: ";

cin >> duration;

cin.ignore(); // ignore return char

Building office;//create the building

cout << endl << "*** ELEVATOR SIMULATION BEGINS ***" << endl << endl;

office.RunSimulation( duration ); // start simulation

cout << "*** ELEVATOR SIMULATION ENDS ***" << endl;

}

Рис. 2.8. Результати виконання програми