Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object Orientied Programming #45

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions src/main/kotlin/ru/otus/cars/Car.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ interface Car : CarInput {
*/
val carOutput: CarOutput

val tankMouth: TankMouth

val tank: Tank
/**
* Получить оборудование
*/
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/ru/otus/cars/CarFactory.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ object Togliatti : CarFactory {

override fun buildCar(builder: CarBuilder, plates: Car.Plates): Car {
return when (builder) {
is Vaz2107.Companion -> return buildVaz2107(plates)
is Vaz2108.Companion -> return buildVaz2108(plates)
is Vaz2107.Companion -> buildVaz2107(plates)
is Vaz2108.Companion -> buildVaz2108(plates)
}
}
}
1 change: 1 addition & 0 deletions src/main/kotlin/ru/otus/cars/CarOutput.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ interface CarOutput {
* Скажи текущую скорость
*/
fun getCurrentSpeed(): Int
fun getFuelContents(): Int
}
19 changes: 19 additions & 0 deletions src/main/kotlin/ru/otus/cars/Tank.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package ru.otus.cars
class Tank(private val capacity: Int) {

var mouth: TankMouth? = null

private var currentFuelLevel: Int = 0
fun getContents(): Int {
return currentFuelLevel
}
fun receiveFuel(liters: Int) {
if (liters < 0) {
println("Ошибка: Нельзя добавить отрицательное количество топлива.")
return
}

currentFuelLevel = (currentFuelLevel + liters).coerceAtMost(capacity)
println("В бак добавлено $liters литров топлива. Текущий уровень: $currentFuelLevel литров.")
}
}
25 changes: 25 additions & 0 deletions src/main/kotlin/ru/otus/cars/TankMouth.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package ru.otus.cars
interface TankMouth {
fun open()
fun close()
}
class PetrolMouth : TankMouth {
override fun open() { println("Открытие горловины для бензина...") }
override fun close() { println("Закрытие горловины для бензина...") }

fun fuelPetrol(tank: Tank, liters: Int) {
open()
tank.receiveFuel(liters)
close()
}
}
class LpgMouth : TankMouth {
override fun open() { println("Открытие горловины для газа...") }
override fun close() { println("Закрытие горловины для газа...") }

fun fuelLpg(tank: Tank, liters: Int) {
open()
tank.receiveFuel(liters)
close()
}
}
24 changes: 17 additions & 7 deletions src/main/kotlin/ru/otus/cars/Taz.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ object Taz: Car {
/**
* Номерной знак
*/
override val plates: Car.Plates
get() = throw NotImplementedError("Номера сняты")
override val plates: Car.Plates = Car.Plates("Без номера", 0)

/**
* Цвет машины
Expand All @@ -15,8 +14,19 @@ object Taz: Car {
/**
* Следит за машиной
*/
override val carOutput: CarOutput
get() = throw NotImplementedError("Приборов нет")
override val carOutput: CarOutput = object : CarOutput {
override fun getCurrentSpeed(): Int = 0
override fun getFuelContents(): Int = 0
}
override val tankMouth: TankMouth = object : TankMouth {
override fun open() {
println("У Taz нет настоящей горловины бака.")
}
override fun close() {
println("У Taz нет настоящей горловины бака.")
}
}
override val tank: Tank = Tank(0)

/**
* Получить оборудование
Expand All @@ -27,13 +37,13 @@ object Taz: Car {
* Руль вправо на [degrees] градусов
*/
override fun wheelToRight(degrees: Int) {
throw NotImplementedError("Руля нет")
println("Руля нет")
}

/**
* Руль влево на [degrees] градусов
*/
override fun wheelToLeft(degrees: Int) {
throw NotImplementedError("Руля нет")
println("Руля нет")
}
}
}
6 changes: 5 additions & 1 deletion src/main/kotlin/ru/otus/cars/Vaz2107.kt
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) {

// Выводим состояние машины
override fun toString(): String {
return "Vaz2107(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed)"
return "Машина ВАЗ 2107: номерной знак - ${plates.number} регион - ${plates.region}, угол поворота руля - $wheelAngle градусов, текущая скорость - $currentSpeed км/ч"
}

/**
Expand All @@ -74,5 +74,9 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) {
override fun getCurrentSpeed(): Int {
return [email protected]
}

override fun getFuelContents(): Int {
return [email protected]()
}
}
}
6 changes: 5 additions & 1 deletion src/main/kotlin/ru/otus/cars/Vaz2108.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) {

// Выводим состояние машины
override fun toString(): String {
return "Vaz2108(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed)"
return "Машина ВАЗ 2108: номерной знак - ${plates.number} регион - ${plates.region}, угол поворота руля - $wheelAngle градусов, текущая скорость - $currentSpeed км/ч"
}

/**
Expand All @@ -78,5 +78,9 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) {
override fun getCurrentSpeed(): Int {
return [email protected]
}

override fun getFuelContents(): Int {
return [email protected]()
}
}
}
17 changes: 17 additions & 0 deletions src/main/kotlin/ru/otus/cars/VazPlatform.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,23 @@ abstract class VazPlatform(override val color: String) : Car {
// Реализация интерфейса CarInput
override fun wheelToLeft(degrees: Int) { wheelAngle -= degrees }

override val tankMouth: TankMouth = object : TankMouth {
private var isOpen = false

override fun open() {
isOpen = true
println("Горловина бака открыта.")
}

override fun close() {
isOpen = false
println("Горловина бака закрыта.")
}
}

override val tank: Tank = Tank(capacity = 50).apply {
mouth = tankMouth
}
// Получить оборудование
override fun getEquipment(): String = "Кузов, колеса, движок"

Expand Down
59 changes: 45 additions & 14 deletions src/main/kotlin/ru/otus/cars/main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,29 @@ package ru.otus.cars

fun main() {
println("\n===> drive cars...")
driveCars()
driveCars() // Запускаем функцию для проверки вождения

println("\n===> inner test...")
innerNestedCheck()
innerNestedCheck() // Проверка внутреннего состояния

println("\n===> garage make...")
garageMake()
garageMake() // Создание машины в гараже

println("\n===> model special...")
// Дополнительные действия для проверки моделей (можно добавить сюда, если нужно)

println("\n===> get equipment...")
getEquipment()
getEquipment() // Проверка оборудования

println("\n===> get color...")
getColor()
getColor() // Проверка цвета

println("\n===> tech checks...")
techChecks()
techChecks() // Проверка технического состояния

println("\n===> fuel tests...")
fuelTestDemo() // Тестирование системы заправки

println("\n===> Taz...")
println(Taz.color)
}
Expand All @@ -29,13 +40,36 @@ fun driveCars() {
println(vaz2.toString()) // Выводит -20 и случайную скорость
}

fun fuelTestDemo() {
val vaz1 = Togliatti.buildCar(Vaz2107, Car.Plates("123", 77))
val vaz2 = Togliatti.buildCar(Vaz2108, Car.Plates("321", 78))

fuelTest(vaz1, 30)
fuelTest(vaz2, 40)
}

fun fuelTest(car: Car, liters: Int) {
println("Текущий уровень топлива для ${car::class.simpleName}: ${car.carOutput.getFuelContents()} литров.")
when (val mouth = car.tankMouth) {
is PetrolMouth -> {
println("Заправляем бензином...")
mouth.fuelPetrol(car.tank, liters)
}
is LpgMouth -> {
println("Заправляем газом...")
mouth.fuelLpg(car.tank, liters)
}
}
println("Уровень топлива после заправки: ${car.carOutput.getFuelContents()} литров.")
}

fun innerNestedCheck() {
val vaz = Vaz2107.build(Car.Plates("123", 77))
val output = vaz.VazOutput() // Создаем новый объект ИЗ ЭКЗЕМПЛЯРА МАШИНЫ
val output = vaz.VazOutput()

println("Скорость до проверки: ${output.getCurrentSpeed()}") // Выводит 0
Vaz2107.test(vaz) // Газуем...
println("Скорость после проверки: ${output.getCurrentSpeed()}") // Выводит случайную скорость
println("Скорость до проверки: ${output.getCurrentSpeed()}")
Vaz2107.test(vaz)
println("Скорость после проверки: ${output.getCurrentSpeed()}")
}

fun garageMake() {
Expand Down Expand Up @@ -83,11 +117,8 @@ fun techChecks() {
}

fun repairEngine(car: VazPlatform) {
// Проверяем тип двигателя
// В зависимости от типа двигателя выполняем разные действия
// when обеспечивает обход всех вариантов перечисления
when (car.engine) {
is VazEngine.LADA_2107 -> println("Чистка карбюратора у двигателя объемом ${car.engine.volume} куб.см у машины $car")
is VazEngine.SAMARA_2108 -> println("Угол зажигания у двигателя объемом ${car.engine.volume} куб.см у машины $car")
}
}
}