Compare commits
33
Commits
4b4ac7f0c9
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0022b101e | ||
|
|
17df4a5812 | ||
|
|
1957cbada0 | ||
|
|
c7214b04b4 | ||
|
|
409b520e69 | ||
|
|
fb5ede78ce | ||
|
|
a7eaa693bd | ||
|
|
8254f5292b | ||
|
|
e64318df27 | ||
|
|
18acbd3b32 | ||
|
|
56038f62f7 | ||
|
|
728cb4f84f | ||
|
|
5140228f3e | ||
|
|
0174224089 | ||
|
|
8c0cc0aa06 | ||
|
|
da878ec81c | ||
|
|
4cd38a9afe | ||
|
|
2c7deaa9ae | ||
|
|
8399ab0d58 | ||
|
|
f0b79f0db0 | ||
|
|
09cbf440ad | ||
|
|
0f8f4037c9 | ||
|
|
65b3ddcc24 | ||
|
|
20f9f7e8df | ||
|
|
0f838ae4a0 | ||
|
|
1f609abcb7 | ||
|
|
99e60947a6 | ||
|
|
f380e12f67 | ||
|
|
28cdd22635 | ||
|
|
0776e220b3 | ||
|
|
8700123455 | ||
|
|
54d80bfc32 | ||
|
|
9b98399b6e |
@@ -1,2 +1,3 @@
|
||||
todo/target/
|
||||
.vscode/
|
||||
.lingma/
|
||||
@@ -0,0 +1,47 @@
|
||||
# Журнал изменений
|
||||
|
||||
Все заметные изменения проекта будут документироваться в этом файле.
|
||||
Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.0.0/),
|
||||
и этот проект придерживается [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
|
||||
|
||||
## [2.2.0] - 2025-06-08
|
||||
|
||||
### Добавлено
|
||||
- Универсальный интерфейс `Identifiable` для всех сущностей с ID
|
||||
- Универсальный класс `EntityService` для стандартных CRUD-операций
|
||||
- Универсальный интерфейс `Repository<T>` для базовых операций с данными
|
||||
- Утилитарный класс `Formatter` с методом `asTable()` для форматирования таблиц
|
||||
|
||||
### Изменено
|
||||
- **[BREAKING]** Обобщение CLI-команд для поддержки разных типов сущностей через `EntityService`
|
||||
- Рефакторинг `TaskService` для расширения `EntityService` вместо собственной реализации
|
||||
- Переименование `InMemoryTaskRepository` → `InMemoryRepository` с поддержкой generics
|
||||
- Унификация работы с моделью `Task` через интерфейс `Identifiable`
|
||||
- Вынесение логики форматирования таблиц из `ListCommand` в отдельный utility-класс
|
||||
- Обновление `ListCommand` и `SearchCommand` для использования `Formatter.asTable()`
|
||||
- Замена метода `list()` на `getAll()` в сервисном слое
|
||||
|
||||
### Технические улучшения
|
||||
- Улучшена типобезопасность через использование generics
|
||||
- Повышена переиспользуемость кода за счёт вынесения общей логики
|
||||
- Упрощена архитектура через унификацию интерфейсов
|
||||
- Удалено дублирование кода форматирования между командами
|
||||
|
||||
## [2.1.0] - 2025-06-01
|
||||
|
||||
### Добавлено
|
||||
- Команда `search <текст>` для поиска задач по тексту (реализован класс `SearchCommand`)
|
||||
- Метод `search(String query)` в `TaskService` для поддержки поиска задач
|
||||
- Рефакторинг: вынесение общего функционала отображения задач в отдельный метод `formatWithTable()` в классе `ListCommand`
|
||||
|
||||
### Изменено
|
||||
- Обновлены внутренние зависимости между компонентами CLI (`SearchCommand`, `ListCommand`) и моделью данных (`Task`, `SimpleTask`)
|
||||
- Добавлена обработка минимальной длины поискового запроса (3 символа) в `SearchCommand`
|
||||
|
||||
## [2.0.0] - 2025-05-29
|
||||
|
||||
### Добавлено
|
||||
- Базовая функциональность для управления задачами
|
||||
- Команды: create, list, delete, complete
|
||||
- Консольный интерфейс для взаимодействия с приложением
|
||||
- In-memory хранилище задач
|
||||
@@ -0,0 +1,92 @@
|
||||
# TodoApp
|
||||
|
||||
## Описание
|
||||
|
||||
TodoApp - это консольное приложение для управления списком задач, разработанное на Java в качестве учебного проекта. Приложение построено на универсальной архитектуре с использованием generics, что позволяет легко расширять функционал для работы с различными типами сущностей.
|
||||
|
||||
|
||||
### Особенности
|
||||
- Консольный интерфейс с интуитивными командами
|
||||
- Универсальная архитектура на базе `EntityService` и `Repository<T>`
|
||||
- Поддержка поиска задач по тексту
|
||||
- Красивое табличное отображение данных
|
||||
- Типобезопасность через использование generics
|
||||
|
||||
|
||||
## Требования
|
||||
|
||||
- Java 24 или выше
|
||||
- Maven 3.8.x или выше
|
||||
|
||||
|
||||
## Установка и запуск
|
||||
|
||||
```bash
|
||||
cd ./todo
|
||||
mvn clean package
|
||||
java -jar ./target/todo.jar
|
||||
```
|
||||
|
||||
|
||||
## Использование
|
||||
|
||||
### Доступные команды
|
||||
- `create <название_задачи>` - Создать новую задачу
|
||||
- `list` - Показать список всех задач в табличном виде
|
||||
- `complete <id>` - Отметить задачу как выполненную
|
||||
- `delete <id>` - Удалить задачу по ID
|
||||
- `search <текст>` - Найти задачи по тексту (минимум 3 символа)
|
||||
- `help` - Показать список всех команд
|
||||
- `exit` - Выйти из приложения
|
||||
|
||||
|
||||
## Пример использования
|
||||
|
||||
```shell
|
||||
todo> create Изучить Java generics
|
||||
Задача "Изучить Java generics" успешно добавлена!
|
||||
|
||||
todo> create Написать документацию
|
||||
Задача "Написать документацию" успешно добавлена!
|
||||
|
||||
todo> list
|
||||
|
||||
ID │ Название задачи │ Статус
|
||||
--------------------------------------------------
|
||||
1 │ Изучить Java generics │ В процессе
|
||||
2 │ Написать документацию │ В процессе
|
||||
|
||||
|
||||
todo> complete 1
|
||||
|
||||
Задача ID-1 выполнена.
|
||||
|
||||
todo> search Java
|
||||
|
||||
ID │ Название задачи │ Статус
|
||||
--------------------------------------------------
|
||||
1 │ Изучить Java generics │ Выполнена
|
||||
|
||||
```
|
||||
|
||||
## Версии
|
||||
|
||||
Актуальная версия: 2.2.0
|
||||
|
||||
### История изменений
|
||||
- 2.2.0 - Универсальная архитектура с generics, утилиты форматирования
|
||||
- 2.1.0 - Добавлена команда поиска, улучшено отображение
|
||||
- 2.0.0 - Базовый функционал управления задачами
|
||||
|
||||
Подробная история изменений доступна в CHANGELOG.md
|
||||
|
||||
### Разработка
|
||||
Проект использует современные подходы Java-разработки:
|
||||
- Generic programming для типобезопасности
|
||||
- Разделение ответственности через слоистую архитектуру
|
||||
- Command pattern для CLI-команд
|
||||
- Repository pattern для работы с данными
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT
|
||||
@@ -1,148 +0,0 @@
|
||||
Inheritance
|
||||
|
||||
In the preceding sections, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.
|
||||
|
||||
Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
|
||||
|
||||
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
|
||||
|
||||
Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.
|
||||
|
||||
The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.
|
||||
|
||||
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
|
||||
|
||||
The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.
|
||||
|
||||
At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior.
|
||||
|
||||
|
||||
An Example of Inheritance
|
||||
|
||||
Here is the sample code for a possible implementation of a Bicycle class that was presented in the Classes and Objects section:
|
||||
|
||||
public class Bicycle {
|
||||
|
||||
// the Bicycle class has three fields
|
||||
public int cadence;
|
||||
public int gear;
|
||||
public int speed;
|
||||
|
||||
// the Bicycle class has one constructor
|
||||
public Bicycle(int startCadence, int startSpeed, int startGear) {
|
||||
gear = startGear;
|
||||
cadence = startCadence;
|
||||
speed = startSpeed;
|
||||
}
|
||||
|
||||
// the Bicycle class has four methods
|
||||
public void setCadence(int newValue) {
|
||||
cadence = newValue;
|
||||
}
|
||||
|
||||
public void setGear(int newValue) {
|
||||
gear = newValue;
|
||||
}
|
||||
|
||||
public void applyBrake(int decrement) {
|
||||
speed -= decrement;
|
||||
}
|
||||
|
||||
public void speedUp(int increment) {
|
||||
speed += increment;
|
||||
}
|
||||
}
|
||||
|
||||
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
|
||||
|
||||
public class MountainBike extends Bicycle {
|
||||
|
||||
// the MountainBike subclass adds one field
|
||||
public int seatHeight;
|
||||
|
||||
// the MountainBike subclass has one constructor
|
||||
public MountainBike(int startHeight,
|
||||
int startCadence,
|
||||
int startSpeed,
|
||||
int startGear) {
|
||||
super(startCadence, startSpeed, startGear);
|
||||
seatHeight = startHeight;
|
||||
}
|
||||
|
||||
// the MountainBike subclass adds one method
|
||||
public void setHeight(int newValue) {
|
||||
seatHeight = newValue;
|
||||
}
|
||||
}
|
||||
|
||||
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you did not have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.
|
||||
|
||||
|
||||
What You Can Do in a Subclass
|
||||
|
||||
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:
|
||||
|
||||
The inherited fields can be used directly, just like any other fields.
|
||||
You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
|
||||
You can declare new fields in the subclass that are not in the superclass.
|
||||
The inherited methods can be used directly as they are.
|
||||
You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
|
||||
You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
|
||||
You can declare new methods in the subclass that are not in the superclass.
|
||||
You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
|
||||
The following sections in this lesson will expand on these topics.
|
||||
|
||||
|
||||
Private Members in a Superclass
|
||||
|
||||
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
|
||||
|
||||
A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
|
||||
|
||||
|
||||
Casting Objects
|
||||
|
||||
We have seen that an object is of the data type of the class from which it was instantiated. For example, if we write
|
||||
|
||||
public MountainBike myBike = new MountainBike();
|
||||
|
||||
then myBike is of type MountainBike.
|
||||
|
||||
MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is a Bicycle and is also an Object, and it can be used wherever Bicycle or Object objects are called for.
|
||||
|
||||
The reverse is not necessarily true: a Bicycle may be a MountainBike, but it is not necessarily. Similarly, an Object may be a Bicycle or a MountainBike, but it is not necessarily.
|
||||
|
||||
Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we write
|
||||
|
||||
Object obj = new MountainBike();
|
||||
|
||||
then obj is both an Object and a MountainBike (until such time as obj is assigned another object that is not a MountainBike). This is called implicit casting.
|
||||
|
||||
If, on the other hand, we write
|
||||
|
||||
MountainBike myBike = obj;
|
||||
|
||||
we would get a compile-time error because obj is not known to the compiler to be a MountainBike. However, we can tell the compiler that we promise to assign a MountainBike to obj by explicit casting:
|
||||
|
||||
MountainBike myBike = (MountainBike)obj;
|
||||
|
||||
This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can safely assume that obj is a MountainBike. If obj is not a MountainBike at runtime, an exception will be thrown.
|
||||
|
||||
Note: You can make a logical test as to the type of a particular object using the instanceof operator. This can save you from a runtime error owing to an improper cast. For example:
|
||||
|
||||
if (obj instanceof MountainBike) {
|
||||
MountainBike myBike = (MountainBike)obj;
|
||||
}
|
||||
|
||||
Here the instanceof operator verifies that obj refers to a MountainBike so that we can make the cast with knowledge that there will be no runtime exception thrown.
|
||||
|
||||
|
||||
Multiple Inheritance of State, Implementation, and Type
|
||||
|
||||
One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot. In addition, you can instantiate a class to create an object, which you cannot do with interfaces. As explained in the section What Is an Object?, an object stores its state in fields, which are defined in classes. One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes. For example, suppose that you are able to define a new class that extends multiple classes. When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. What if methods or constructors from different superclasses instantiate the same field? Which method or constructor will take precedence? Because interfaces do not contain fields, you do not have to worry about problems that result from multiple inheritance of state.
|
||||
|
||||
Multiple inheritance of implementation is the ability to inherit method definitions from multiple classes. Problems arise with this type of multiple inheritance, such as name conflicts and ambiguity. When compilers of programming languages that support this type of multiple inheritance encounter superclasses that contain methods with the same name, they sometimes cannot determine which member or method to access or invoke. In addition, a programmer can unwittingly introduce a name conflict by adding a new method to a superclass. Default methods introduce one form of multiple inheritance of implementation. A class can implement more than one interface, which can contain default methods that have the same name. The Java compiler provides some rules to determine which default method a particular class uses.
|
||||
|
||||
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface. An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements. This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface. This is discussed in the section Using an Interface as a Type.
|
||||
|
||||
As with multiple inheritance of implementation, a class can inherit different implementations of a method defined (as default or static) in the interfaces that it extends. In this case, the compiler or the user must decide which one to use.
|
||||
+31
-1
@@ -6,10 +6,40 @@
|
||||
|
||||
<groupId>ru.kamask.pet</groupId>
|
||||
<artifactId>todo</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<version>2.2.0</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>24</maven.compiler.release>
|
||||
<maven.compiler.target>24</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>todo</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>ru.kamask.pet.todo.TodoApp</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.0</version>
|
||||
<configuration>
|
||||
<source>24</source>
|
||||
<target>24</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -3,12 +3,13 @@ package ru.kamask.pet.todo;
|
||||
import java.io.IOException;
|
||||
|
||||
import ru.kamask.pet.todo.cli.CliEngine;
|
||||
import ru.kamask.pet.todo.repo.InMemoryTaskRepository;
|
||||
import ru.kamask.pet.todo.model.SimpleTask;
|
||||
import ru.kamask.pet.todo.repo.InMemoryRepository;
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
|
||||
public class TodoApp {
|
||||
public static void main(String[] args) throws IOException {
|
||||
var service = new TaskService(new InMemoryTaskRepository());
|
||||
var service = new TaskService(new InMemoryRepository<SimpleTask>());
|
||||
var cli = new CliEngine(service);
|
||||
|
||||
cli.start();
|
||||
|
||||
@@ -7,21 +7,22 @@ import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
|
||||
public class CliEngine {
|
||||
private HashMap<String, Command> registry = new HashMap<>();
|
||||
private TaskService service;
|
||||
private EntityService<? extends Identifiable> service;
|
||||
private BufferedReader reader;
|
||||
|
||||
public CliEngine(TaskService service) {
|
||||
public CliEngine(EntityService<? extends Identifiable> service) {
|
||||
this.service = service;
|
||||
reader = new BufferedReader(new InputStreamReader(System.in));
|
||||
initializeCommands();
|
||||
}
|
||||
|
||||
public void start() throws IOException {
|
||||
System.out.println("\nДобро пожаловать в Список задач 2.0!");
|
||||
System.out.println("\nДобро пожаловать в Список задач 2.2!");
|
||||
System.out.println("Введите help для просмтора доступных команд или exit для выхода.");
|
||||
while (true) {
|
||||
System.out.print("\ntodo> ");
|
||||
@@ -46,6 +47,7 @@ public class CliEngine {
|
||||
registerCommand(new CreateCommand());
|
||||
registerCommand(new ListCommand());
|
||||
registerCommand(new CompleteCommand());
|
||||
registerCommand(new SearchCommand());
|
||||
registerCommand(new DeleteCommand());
|
||||
}
|
||||
|
||||
|
||||
@@ -2,13 +2,14 @@ package ru.kamask.pet.todo.cli;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
|
||||
public interface Command {
|
||||
String templateUsage = " %-30s // %s";
|
||||
String errorMessage = "Не корректно введена команда. Введите help для спарвки.";
|
||||
|
||||
Optional<String> handle(String[] args, TaskService service);
|
||||
Optional<String> handle(String[] args, EntityService<? extends Identifiable> service);
|
||||
|
||||
String name();
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package ru.kamask.pet.todo.cli;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
|
||||
public class CompleteCommand implements Command {
|
||||
@@ -16,14 +18,16 @@ public class CompleteCommand implements Command {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> handle(String[] args, TaskService service) {
|
||||
public Optional<String> handle(String[] args, EntityService<? extends Identifiable> service) {
|
||||
if (args.length != 1)
|
||||
return Optional.of(Command.errorMessage);
|
||||
|
||||
TaskService taskService = (TaskService) service;
|
||||
|
||||
try {
|
||||
int id = Integer.parseInt(args[0]);
|
||||
|
||||
return Optional.of(service.complete(id)
|
||||
return Optional.of(taskService.complete(id)
|
||||
? "Задача ID-%d выполнена.".formatted(id)
|
||||
: "Задача ID-%d не найдена.".formatted(id));
|
||||
|
||||
|
||||
@@ -2,21 +2,24 @@ package ru.kamask.pet.todo.cli;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
|
||||
public class CreateCommand implements Command {
|
||||
public class CreateCommand implements Command{
|
||||
@Override
|
||||
public String name() {
|
||||
return "create";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> handle(String[] args, TaskService service) {
|
||||
public Optional<String> handle(String[] args, EntityService<? extends Identifiable> service) {
|
||||
if (args.length > 0) {
|
||||
var title = String.join(" ", args);
|
||||
if (title.length() > 30)
|
||||
return Optional.of("Ошибка: максимальная длинна названия задачи 30 символов.");
|
||||
service.create(title);
|
||||
TaskService taskService = (TaskService) service;
|
||||
taskService.create(title);
|
||||
return Optional.of(String.format("Задача \"%s\" успешно добавлена!", title));
|
||||
}
|
||||
return Optional.of(Command.errorMessage);
|
||||
|
||||
@@ -2,9 +2,10 @@ package ru.kamask.pet.todo.cli;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
|
||||
public class DeleteCommand implements Command {
|
||||
public class DeleteCommand implements Command{
|
||||
@Override
|
||||
public String name() {
|
||||
return "delete";
|
||||
@@ -16,7 +17,7 @@ public class DeleteCommand implements Command {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> handle(String[] args, TaskService service) {
|
||||
public Optional<String> handle(String[] args, EntityService<? extends Identifiable> service) {
|
||||
if (args.length != 1)
|
||||
return Optional.of(Command.errorMessage);
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@ package ru.kamask.pet.todo.cli;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.SimpleTask;
|
||||
import ru.kamask.pet.todo.model.Task;
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
import ru.kamask.pet.todo.util.Formatter;
|
||||
|
||||
public class ListCommand implements Command {
|
||||
@Override
|
||||
@@ -13,23 +14,13 @@ public class ListCommand implements Command {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> handle(String[] args, TaskService service) {
|
||||
public Optional<String> handle(String[] args, EntityService<? extends Identifiable> service) {
|
||||
if (args.length > 0)
|
||||
return Optional.of(Command.errorMessage);
|
||||
|
||||
String template = "%-2s | %-30s | %s\n";
|
||||
String res = "";
|
||||
res += String.format(template, "ID", "Название задачи", "Статус");
|
||||
res += "-".repeat(50) + "\n";
|
||||
|
||||
if (service.list().size() == 0)
|
||||
return Optional.of(res + "\nСписок задач пуст.");
|
||||
|
||||
for (Task task : service.list()) {
|
||||
SimpleTask.Data data = ((SimpleTask) task).data();
|
||||
res += String.format(template, data.id(), data.title(), data.done() ? "выполнено" : "не выполнено");
|
||||
}
|
||||
return Optional.of(res);
|
||||
TaskService taskService = (TaskService) service;
|
||||
|
||||
return Optional.of(Formatter.asTable(taskService.getAll()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package ru.kamask.pet.todo.cli;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.service.EntityService;
|
||||
import ru.kamask.pet.todo.service.TaskService;
|
||||
import ru.kamask.pet.todo.util.Formatter;
|
||||
|
||||
public class SearchCommand implements Command {
|
||||
@Override
|
||||
public String name() {
|
||||
return "search";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String usage() {
|
||||
return String.format(templateUsage, name() + " <текст>", "Поиск задач по тексту (минимум 3 символа)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> handle(String[] args, EntityService<? extends Identifiable> service) {
|
||||
if (args.length != 1)
|
||||
return Optional.of(Command.errorMessage);
|
||||
if (args[0].length() < 3)
|
||||
return Optional.of("Длина запроса должна быть не менее 3 символов.");
|
||||
|
||||
TaskService taskService = (TaskService) service;
|
||||
|
||||
var matchTask = taskService.search(args[0]);
|
||||
|
||||
return Optional.of(Formatter.asTable(matchTask, "Не найдено задач, соответствующих запросу."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.kamask.pet.todo.model;
|
||||
|
||||
public interface Identifiable {
|
||||
int getId();
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package ru.kamask.pet.todo.model;
|
||||
|
||||
public abstract class Task {
|
||||
public abstract class Task implements Identifiable{
|
||||
private static int nextId = 1;
|
||||
|
||||
protected int id;
|
||||
@@ -11,10 +11,15 @@ public abstract class Task {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public int id() {
|
||||
@Override
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public int id() {
|
||||
return getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Задача: id - %d, title: \"%s\"", id, title);
|
||||
|
||||
+7
-7
@@ -6,23 +6,23 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Task;
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
|
||||
public class InMemoryTaskRepository implements TaskRepository {
|
||||
private Map<Integer, Task> storage = new HashMap<>();
|
||||
public class InMemoryRepository<T extends Identifiable> implements Repository<T> {
|
||||
private Map<Integer, T> storage = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void save(Task task) {
|
||||
storage.put(task.id(), task);
|
||||
public void save(T obj) {
|
||||
storage.put(obj.getId(), obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Task> findById(int id) {
|
||||
public Optional<T> findById(int id) {
|
||||
return Optional.ofNullable(storage.get(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Task> findAll() {
|
||||
public List<T> findAll() {
|
||||
return new ArrayList<>(storage.values());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.kamask.pet.todo.repo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
|
||||
public interface Repository<T extends Identifiable> {
|
||||
void save(T obj);
|
||||
Optional<T> findById(int id);
|
||||
List<T> findAll();
|
||||
void delete(int id);
|
||||
boolean has(int id);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package ru.kamask.pet.todo.repo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Task;
|
||||
|
||||
public interface TaskRepository {
|
||||
void save(Task task);
|
||||
|
||||
Optional<Task> findById(int id);
|
||||
|
||||
List<Task> findAll();
|
||||
|
||||
void delete(int id);
|
||||
|
||||
boolean has(int id);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package ru.kamask.pet.todo.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Identifiable;
|
||||
import ru.kamask.pet.todo.repo.Repository;
|
||||
|
||||
public class EntityService<T extends Identifiable> {
|
||||
private final Repository<T> repo;
|
||||
|
||||
protected EntityService(Repository<T> repo) {
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
public void save(T obj) {
|
||||
repo.save(obj);
|
||||
}
|
||||
|
||||
public Optional<T> getById(int id) {
|
||||
return repo.findById(id);
|
||||
}
|
||||
|
||||
public List<T> getAll() {
|
||||
return repo.findAll();
|
||||
}
|
||||
|
||||
public void remove(int id) {
|
||||
repo.delete(id);
|
||||
}
|
||||
|
||||
public boolean has(int id) {
|
||||
return repo.has(id);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,23 @@
|
||||
package ru.kamask.pet.todo.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import ru.kamask.pet.todo.model.Task;
|
||||
import ru.kamask.pet.todo.model.SimpleTask;
|
||||
import ru.kamask.pet.todo.repo.TaskRepository;
|
||||
import ru.kamask.pet.todo.repo.Repository;
|
||||
|
||||
public class TaskService {
|
||||
private final TaskRepository repo;
|
||||
public class TaskService extends EntityService<SimpleTask> {
|
||||
|
||||
public TaskService(TaskRepository repo) {
|
||||
this.repo = repo;
|
||||
public TaskService(Repository<SimpleTask> repo) {
|
||||
super(repo);
|
||||
}
|
||||
|
||||
public void create(String title) {
|
||||
repo.save(new SimpleTask(title));
|
||||
super.save(new SimpleTask(title));
|
||||
}
|
||||
|
||||
public Optional<Task> getById(int id) {
|
||||
return repo.findById(id);
|
||||
}
|
||||
|
||||
public boolean complete(int id) {
|
||||
var taskOpt = repo.findById(id);
|
||||
var taskOpt = super.getById(id);
|
||||
if (taskOpt.isPresent()) {
|
||||
taskOpt.get().markAsCompleted();
|
||||
return true;
|
||||
@@ -31,15 +25,10 @@ public class TaskService {
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<Task> list() {
|
||||
return repo.findAll();
|
||||
}
|
||||
|
||||
public void remove(int id) {
|
||||
repo.delete(id);
|
||||
}
|
||||
|
||||
public boolean has(int id) {
|
||||
return repo.has(id);
|
||||
public List<SimpleTask> search(String query) {
|
||||
return super.getAll().stream()
|
||||
.filter(task -> task.data().title().contains(query))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package ru.kamask.pet.todo.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import ru.kamask.pet.todo.model.SimpleTask;
|
||||
|
||||
public class Formatter {
|
||||
public static String asTable(List<SimpleTask> tasks){
|
||||
return asTable(tasks, "Список задач пуст.");
|
||||
}
|
||||
|
||||
public static String asTable(List<SimpleTask> tasks, String msgIfEmpty){
|
||||
String template = "%-2s | %-30s | %s\n";
|
||||
var res = new StringBuilder(String.format(template, "ID", "Название задачи", "Статус"));
|
||||
res.append("-".repeat(50) + "\n");
|
||||
|
||||
if (tasks.size() == 0)
|
||||
return res.append("\n" + msgIfEmpty).toString();
|
||||
|
||||
for (SimpleTask task : tasks) {
|
||||
SimpleTask.Data data = task.data();
|
||||
res.append(String.format(template, data.id(), data.title(), data.done() ? "выполнено" : "не выполнено"));
|
||||
}
|
||||
|
||||
return res.toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user