Материал: Паттерны проектирования программных систем (90

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам

<< (total % 100 < 10 ? "0" : "") << total % 100 << endl; cout << "quarters - " << slots[0]->getCount() << endl;

cout << "dimes - " << slots[1]->getCount() << endl; cout << "nickels - " << slots[2]->getCount() << endl; cout << "pennies - " << slots[3]->getCount() << endl;

}

//10 5 25 5 1 25 5 25 1 25

//total deposited is $1.27

//quarters - 4

//dimes - 1

//nickels - 3

//pennies - 2

//

//25 25 10 5 1 5 10 5 1 5

//total deposited is $0.92

//quarters - 2

//dimes - 2

//nickels - 4

//pennies - 2

//

//5 10 25 10 25 1 25 10 1 25

//total deposited is $1.37

//quarters - 4

//dimes - 3

//nickels - 1

//pennies - 2

2.2. Команда.

Необходимо реализовать командный интерфейс с поддержкой очереди

команд. Поддерживаемые команды – сжатие, распаковка и передача файла.

#include <iostream.h> #include <string.h> struct Command;

class Queue { public:

Queue() {

add_ = remove_ = 0;

}

void enque(Command* c) { array_[add_] = c;

add_ = (add_ + 1) % SIZE;

}

Command* deque() {

int temp = remove_;

remove_ = (remove_ + 1) % SIZE; return array_[temp];

}

private:

enum { SIZE = 10 }; Command* array_[SIZE]; int add_;

int remove_;

};

class File { public:

File(char* n) { strcpy(name_, n); }

25

void unarchive() { cout << "unarchive " << name_ << endl; } void compress() { cout << "compress " << name_ << endl; } void transfer() { cout << "transfer " << name_ << endl; }

private:

char name_[30];

};

enum Action { unarchive, transfer, compress }; struct Command {

Command(File* f, Action a) { receiver = f; action = a; } File* receiver;

Action action;

};

Command* input[8] = {

new Command(new File("irImage.dat"), unarchive), new Command(new File("screenDump.jpg"), transfer), new Command(new File("paper.ps"), unarchive),

new Command(new File("widget.tar"), compress),

new Command(new File("esmSignal.dat"), unarchive), new Command(new File("msword.exe"), transfer),

new Command(new File("ecmSignal.dat"), compress), new Command(new File("image.gif"), transfer)

};

void main(void)

{

Queue que; Command* cmd; int i;

for (i = 0; i < 8; i++) que.enque(input[i]);

for (i = 0; i < 8; i++)

{

cmd = que.deque();

if (cmd->action == unarchive) cmd->receiver->unarchive();

else if (cmd->action == transfer) cmd->receiver->transfer();

else if (cmd->action == compress) cmd->receiver->compress();

}

}

//unarchive irImage.dat

//transfer screenDump.jpg

//unarchive paper.ps

//compress widget.tar

//unarchive esmSignal.dat

//transfer msword.exe

//compress ecmSignal.dat

//transfer image.gif

2.3. Итератор.

Реализовать обход бинарного дерева с возможностью управления

обходом.

#include <iostream.h> #include <stdlib.h> #include <time.h> struct Node {

int value; Node* left; Node* right; Node() { left = right = 0; }

26

friend ostream& operator<< (ostream& os, Node& n) { return os << n.value;

}

};

class BST { private:

Node* root; int size;

public: BST() {

root = 0;

}

void add(int in) {

if (root == 0) {

root = new Node; root->value = in; size = 1;

return;

}

add(in, root);

}

void traverse() { traverse(root); } private:

void add(int in, Node* current) { if (in < current->value)

if (current->left == 0) { current->left = new Node(); current->left->value = in; size++;

}

else add(in, current->left);

else

if (current->right == 0) { current->right = new Node(); current->right->value = in; size++;

}

else add(in, current->right);

}

void traverse(Node* current) {

if (current->left != 0) traverse(current->left); cout << current->value << " ";

if (current->right != 0) traverse(current->right);

}

};

void main(void) { BST bst; time_t t;

srand((unsigned)time(&t)); cout << "original: ";

for (int i = 0, val; i < 15; i++) { val = rand() % 49 + 1;

cout << val << " "; bst.add(val);

}

cout << "\ntraverse: "; bst.traverse();

cout << endl;

}

//original: 11 43 7 2 22 3 25 40 41 36 32 11 24 11 37

//traverse: 2 3 7 11 11 11 22 24 25 32 36 37 40 41 43

//Iterator: 2 3 7 11 11 11 22 24 25 32 36 37 40 41 43

//Iterator: 2 3 7 11 11 11 22 24 25 32 36 37 40 41 43

27

2.4. Хранитель.

Реализовать игру, состоящую из нескольких раундов, в которой несколько участников угадывают случайное число. Каждый клиент подключается отдельно и отгадывает свое число.

#include <stdlib.h> #include <time.h> #include <string.h> class GuessGame { private:

int numbers[10]; char names[10][20]; int total;

public: GuessGame() {

time_t t; srand((unsigned)time(&t)); total = 0;

}

void join(char* name) { strcpy(names[total], name); numbers[total++] = rand() % 30 + 1;

}

int evaluateGuess(char* name, int guess) { int i;

for (i = 0; i < total; i++)

if (!strcmp(names[i], name)) break; if (guess == numbers[i]) return 0; return ((guess > numbers[i]) ? 1 : -1);

}

};

struct Game {

char name[20];

int min, max, done;

Game() { min = 1; max = 30; done = 0; }

};

void main(void) {

GuessGame guessServer; const int MAX = 3; Game games[MAX];

int gamesComplete = 0; int guess, ret;

for (int i = 0; i < MAX; i++) { cout << "Enter name: "; cin >> games[i].name;

guessServer.join(games[i].name);

}

while (gamesComplete != MAX) {

for (int j = 0; j < MAX; j++) { if (games[j].done) continue;

cout << games[j].name << " ("<<games[j].min << '-' << games[j].max << "): ";

cin >> guess;

ret = guessServer.evaluateGuess(games[j].name, guess); if (ret == 0) {

cout << " lights!! sirens!! balloons!!" << endl; games[j].done = 1;

gamesComplete++;

}

28

else if (ret < 0) {

cout << " too low" << endl; games[j].min = guess;

}

else {

cout << " too high" << endl; games[j].max = guess;

}

}

}

}

//Enter name: Tom

//Enter name: Dick

//Enter name: Harry

//Tom (1-30): 10

//too low

//Dick (1-30): 15

//too high

//Harry (1-30): 20

//too high

//Tom (10-30): 22

//too high

//Dick (1-15): 8

//lights!! sirens!! balloons!!

//Harry (1-20): 10

//too low

//Tom (10-22): 16

//too high

//Harry (10-20): 15

//too low

//Tom (10-16): 13

//too high

//Harry (15-20): 17

//too low

//Tom (10-13): 11

//lights!! sirens!! balloons!!

//Harry (17-20): 18

//lights!! sirens!! balloons!!

2.5.Состояние.

Реализовать переключение состояний конечного автомата:

Команда

on

off

ack

Состояние A

A

B

C

Состояние B

 

A

C

Состояние C

 

 

B

#include <iostream.h> enum State { A, B, C };

enum Message { on, off, ack }; State currentState;

Message messageArray[10] = { on, off, off, ack, ack, ack, ack, on, off, off }; void main(void) {

currentState = B;

for (int index = 0; index < 10; index++) { if (currentState == A) {

if (messageArray[index] == on) {

29

Источник: https://studfile.net/preview/16724806/