Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 3 additions & 78 deletions src/edu/androidclub/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,103 +5,28 @@

import java.util.Stack;

/*
Главный класс нашей программы - представляет собой само приложение.
Реализуем интерфейс Runnable - обозачаем, что этот класс (наше приложение) ЗАПУСКАЕМО,
или имеет метод run()
*/
public class Application implements Runnable {


/*
Храним статический экземпляр нашего приложения
*/
private static Application app;

/*
Точка входа в ПРОГРАММУ
*/
public static void main(String[] args) {
// Создаем экземпляр приложения в статической переменной и запускаем его
app = new Application();
app.run();
}

/*
С помощью этого метода мы в любом участке кода (тк public static) можем получить наше приложение,
причём полученный экземпляр будет ОДИНАКОВЫМ ДЛЯ КАЖДОГО ВЫЗОВА МЕТОДА

(паттерн Singleton)
*/
public static Application getInstance() {
if (app == null) { // Если не создан - создаём
if (app == null) {
app = new Application();
}
return app;
}

/*
Метод запуска приложения как объекта. Определён интерфейсом
*/
@Override
public void run() {
test();
Runnable va = new VendingAutomat();
va.run();
}

/*
Метод тестирования нашего приложения.
Здесь мы создадим случайные данные о продуктах и заполним ими наш "автомат", чтобы протестировать то, что
уже написано
*/
private void test() {
// Создадим схему продуктов (пустую)
ItemInfoScheme itemScheme = new ItemInfoScheme();
// Создадим наборы продуктов для ячеек схемы (пустые)
Stack<Item> colas = new Stack<>(); // 1
Stack<Item> sprites = new Stack<>(); // 2

// Заполним наши наборы продуктами
colas.push(new Cola());
colas.push(new Cola());
colas.push(new Cola());
sprites.push(new Sprite());
sprites.push(new Sprite());

// Создадим объекты-координаты наших наборов продуктов в схеме
Coordinates colaCors = new Coordinates(1, 1);
Coordinates spriteCors = new Coordinates(1, 2);

// Поместии наборы продуктов в схему
itemScheme.put(colaCors, colas);
itemScheme.put(spriteCors, sprites);

// Создадим нашу витрину (коробку продуктов) на основании схемы
ItemBox itemBox = new ProductsBox(itemScheme);

// Протестируем схему - заставим витрину выдавать объекты на заданных координатах
System.out.println( // Напечатать в консоль
itemBox.emit( // Выдать предмет
new Coordinates(1, 1) // Указываем координату
)
.getName() // Получить имя предмета
); // OK
System.out.println(itemBox.emit(new Coordinates(1, 1)).getName()); // OK
System.out.println(itemBox.emit(new Coordinates(1, 1)).getName()); // OK

System.out.println(itemBox.emit(new Coordinates(1, 1)).getName()); // FAIL - предметы кончились в ячейке
}

// Опишем Колу как подкласс Предмета
public static class Cola extends Item {
public Cola() {
super("Cola"); // Вызов конструктора класса-родителя (класса Item)
}
}

// Опишем Спрайт как подкласс Предмета
public static class Sprite extends Item {
public Sprite() {
super("Sprite");
}
}
}
28 changes: 28 additions & 0 deletions src/edu/androidclub/Command.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package edu.androidclub;

public class Command {
public static final String TYPE_GET = "get";

private final String type;
private final Object data;

public Command(String type, Object data) {
this.type = type;
this.data = data;
}

public String getType() {
return type;
}

public Object getData() {
return data;
}

@Override
public String toString() {
return "Command: { type = " + type
+ ", data = " + data
+ " }";
}
}
47 changes: 47 additions & 0 deletions src/edu/androidclub/ConsoleInput.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package edu.androidclub;

import edu.androidclub.domain.Keypad;
import org.omg.CORBA.CODESET_INCOMPATIBLE;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ConsoleInput implements Keypad {

@Override
public Command readCommand() {
InputStream in = System.in;
InputStreamReader reader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = "";
try {
line = bufferedReader.readLine();
} catch (IOException ioex) {
System.err.println(ioex.toString());
System.exit(0);
}
return getCommandByString(line);
}

private Command getCommandByString(String input) {
Command result = null;
String typeStr = input.trim().substring(0, input.lastIndexOf(' '));
String dataStr = input.trim().substring(input.lastIndexOf(' ') + 1, input.length());

int data = Integer.valueOf(dataStr);
int x = data / 10;
int y = data % 10;

if (typeStr.equals(Command.TYPE_GET)) {
result = new Command(
Command.TYPE_GET,
new Coordinates(x, y)
);
}

return result;
}

}
25 changes: 25 additions & 0 deletions src/edu/androidclub/ConsoleScreen.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package edu.androidclub;

import edu.androidclub.domain.AppScreen;

import java.io.PrintStream;

public class ConsoleScreen implements AppScreen {

private static final String LINE_BORDER = "###";

private final PrintStream ps = System.out;

@Override
public void printText(String text) {
ps.println(LINE_BORDER + " " + text + " " + LINE_BORDER);
}

@Override
public void clear() {
for (int i = 0; i < 15; i++) {
ps.println();
}
}

}
14 changes: 14 additions & 0 deletions src/edu/androidclub/ProductsBox.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ public Item emit(Coordinates coordinates) {
// Возвращаем верхний элемент и удаляем его с вершины стопки
return items.pop();
}


public String thereAre(Coordinates coordinates) {
Stack<Item> items = scheme.get(coordinates);
if (items.empty()) {
return "Запрашиваемого предмета нет";
}
else{
return "Запрашиваемый предмет есть";
}
}
}


Expand All @@ -48,3 +59,6 @@ public Item emit(Coordinates coordinates) {






79 changes: 79 additions & 0 deletions src/edu/androidclub/VendingAutomat.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package edu.androidclub;

import edu.androidclub.domain.AppScreen;
import edu.androidclub.domain.Item;
import edu.androidclub.domain.ItemBox;
import edu.androidclub.domain.Keypad;
import edu.androidclub.items.Cola;
import edu.androidclub.items.Fanta;
import edu.androidclub.items.Pulpy;
import edu.androidclub.items.Sprite;

import java.util.Stack;

public class VendingAutomat implements Runnable {

private Keypad keypad = new ConsoleInput();
private ItemBox itemBox = null;
private AppScreen screen = new ConsoleScreen();

@Override
public void run() {
populateItemBox();
while (true) {
requestCommand();
}
}

private void requestCommand() {
screen.printText(
"Hi dear User! Enter 'get #' where # is a product number to get it: "
);
Command userCommand = keypad.readCommand();
if (userCommand.getType().equals(Command.TYPE_GET)) {
Item item = itemBox.emit((Coordinates) userCommand.getData());
if (item == null) {
screen.printText("No items left");
} else {
screen.printText(item.getName() + " " + item.getCost());
}
}
}

private void populateItemBox() {
ItemInfoScheme scheme = new ItemInfoScheme();
Stack<Item> items11 = new Stack<>();
Stack<Item> items12 = new Stack<>();
Stack<Item> items21 = new Stack<>();
Stack<Item> items22 = new Stack<>();

populateStack(items11, "Cola", 15);
populateStack(items12, "Fanta", 2);
populateStack(items21, "Sprite", 1);
populateStack(items22, "Pulpy", 5);

scheme.put(new Coordinates(1, 1), items11);
scheme.put(new Coordinates(1, 2), items12);
scheme.put(new Coordinates(2, 1), items21);
scheme.put(new Coordinates(2, 2), items22);

itemBox = new ProductsBox(scheme);
}

private void populateStack(Stack<Item> stack, String name, int count) {
for (int i = 0; i < count; i++) {
if (name.equals("Cola")) {
stack.push(new Cola());
}
if (name.equals("Sprite")) {
stack.push(new Sprite());
}
if (name.equals("Fanta")) {
stack.push(new Fanta());
}
if (name.equals("Pulpy")) {
stack.push(new Pulpy());
}
}
}
}
8 changes: 7 additions & 1 deletion src/edu/androidclub/domain/Item.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@
// Он тоже неизменяемый - т.к. все поля final
public abstract class Item {
private final String name;
private final int cost;

public Item(String name) {
public Item(String name, int cost) {
this.name = name;
this.cost = cost;
}

// Получить имя
public String getName() {
return name;
}

public int getCost() {
return cost;
}
}
2 changes: 1 addition & 1 deletion src/edu/androidclub/domain/ItemBox.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ public interface ItemBox {

/* Выдать предмет по его координатам */
Item emit(Coordinates coordinates);

String thereAre(Coordinates coordinates);
}
9 changes: 9 additions & 0 deletions src/edu/androidclub/domain/Keypad.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package edu.androidclub.domain;

import edu.androidclub.Command;

public interface Keypad {

Command readCommand();

}
11 changes: 11 additions & 0 deletions src/edu/androidclub/items/Cola.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package edu.androidclub.items;

import edu.androidclub.domain.Item;

public class Cola extends Item {

public Cola() {
super("Cola", 45);
}

}
9 changes: 9 additions & 0 deletions src/edu/androidclub/items/Fanta.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package edu.androidclub.items;

import edu.androidclub.domain.Item;

public class Fanta extends Item{
public Fanta() {
super("Fanta", 45);
}
}
11 changes: 11 additions & 0 deletions src/edu/androidclub/items/Pulpy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package edu.androidclub.items;

import edu.androidclub.domain.Item;

public class Pulpy extends Item {

public Pulpy() {
super("Pulpy", 100);
}

}
Loading