diff --git a/README.md b/README.md index 466cb7f..ad14ad0 100644 --- a/README.md +++ b/README.md @@ -15,14 +15,14 @@ ### Задание 1. Создание топливной систем -- Топливная система машины будет состоять из бака(`Tank`) и горловины (`TankMouth`) -- Бак (его реализация) спрятана от пользователя машины -- Машина заправляется через горловину бака -- Горловина может принимать или бензин, или сжиженный газ -- Уровень бензина доступен водителю через интерфейс `CarOutput` (добавить метод в интерфейс) +- Топливная система машины будет состоять из бака(`Tank`) и горловины (`TankMouth`) + +- Бак (его реализация) спрятана от пользователя машины + +- Машина заправляется через горловину бака + +- Горловина может принимать или бензин, или сжиженный газ + +- Уровень бензина доступен водителю через интерфейс `CarOutput` (добавить метод в интерфейс)+ - Считаем, что бак может принимать и бензин, и газ. Что именно туда заливается - определяется - горловиной, которая установлена на баке -- Топливная система должна устанавливаться "специалистом" - сборщиком нашей машины + горловиной, которая установлена на баке + +- Топливная система должна устанавливаться "специалистом" - сборщиком нашей машины+ Интерфейс бака и его связь с другими компонентами может выглядеть, например, вот так: ![LCE state diagram](http://www.plantuml.com/plantuml/proxy?src=https://raw.githubusercontent.com/Android-Developer-Basic/Kotlin-6/master/doc/Tank.puml) diff --git a/build.gradle b/build.gradle index dcb6872..b412722 100644 --- a/build.gradle +++ b/build.gradle @@ -1,15 +1,23 @@ plugins { - id 'org.jetbrains.kotlin.jvm' version '2.2.10' -} - -kotlin { - jvmToolchain(17) + id 'org.jetbrains.kotlin.jvm' version '2.0.21' } test { useJUnitPlatform() } +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +kotlin { + jvmToolchain(21) +} + group 'ru.otus' version '1.0-SNAPSHOT' @@ -18,6 +26,7 @@ repositories { } dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib" + + implementation("org.jetbrains.kotlin:kotlin-stdlib:2.0.21") implementation 'org.junit.jupiter:junit-jupiter:5.8.1' -} \ No newline at end of file +} diff --git a/src/main/kotlin/ru/otus/cars/Car.kt b/src/main/kotlin/ru/otus/cars/Car.kt index 559978c..68632eb 100644 --- a/src/main/kotlin/ru/otus/cars/Car.kt +++ b/src/main/kotlin/ru/otus/cars/Car.kt @@ -19,6 +19,11 @@ interface Car : CarInput { */ val carOutput: CarOutput + /** + * Топливная система авто + */ + val fuelSystem:FuelSystem + /** * Получить оборудование */ diff --git a/src/main/kotlin/ru/otus/cars/CarOutput.kt b/src/main/kotlin/ru/otus/cars/CarOutput.kt index 875339f..f4bbfbe 100644 --- a/src/main/kotlin/ru/otus/cars/CarOutput.kt +++ b/src/main/kotlin/ru/otus/cars/CarOutput.kt @@ -8,4 +8,5 @@ interface CarOutput { * Скажи текущую скорость */ fun getCurrentSpeed(): Int + fun getFuelLevel(): Int } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/cars/FuelStation.kt b/src/main/kotlin/ru/otus/cars/FuelStation.kt new file mode 100644 index 0000000..452590d --- /dev/null +++ b/src/main/kotlin/ru/otus/cars/FuelStation.kt @@ -0,0 +1,41 @@ +package ru.otus.cars + +import java.lang.RuntimeException + +class FuelStation { + companion object { + + private lateinit var currentCar: Car + fun refuelCar(car: Car, litres: Int) { + println("Заправка авто: ${car.toString()} на ${litres.toString()} литров") + currentCar = car + if( currentCar is Taz){ + throw RuntimeException("ТАЗ НЕ УМЕЕТ ЗАПРАВЛЯТЬСЯ") + } + + val isOk = when(car.fuelSystem.tankMouth.type){ + Type.GAS, Type.FUEL -> { + addFuel(litres) + true + } + else -> { + println("Не обслуживаентся") + false + } + } + if(isOk) + println("Заправлено. Уровень топлива в авто: ${car.carOutput.getFuelLevel()} литров") + else + println("Не заправлено. Уровень топлива в авто: ${car.carOutput.getFuelLevel()} литров") + + println("") + + } + + private fun addFuel(litres: Int): Boolean { + return currentCar.fuelSystem.tankMouth.addFuel(litres) + } + + } + +} \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/cars/FuelSystem.kt b/src/main/kotlin/ru/otus/cars/FuelSystem.kt new file mode 100644 index 0000000..85d0b2d --- /dev/null +++ b/src/main/kotlin/ru/otus/cars/FuelSystem.kt @@ -0,0 +1,62 @@ +package ru.otus.cars + +/** + * Тип топлива: Бензин или Газ + */ +enum class Type{ + FUEL, GAS +} +interface Tank{ + var level: Int +} + +/** + * Горловина к топливному баку + */ +data class TankMouth(val type:Type, val tank:Tank){ + /** + * Заправка бака топливом через горловину + * @param level - сколько залить в бак + * @return сколько в баке после заправки + */ + fun addFuel(level: Int): Boolean { + val fuelLevelBefore = this.tank.level + this.tank.level += level + return (this.tank.level - fuelLevelBefore > 0) + } +} + +class FuelSystem { + private var tank:Tank // Топливный бак + var tankMouth: TankMouth // Горловина бака + constructor(fuelType:Type){ + when(fuelType){ + Type.FUEL -> { + this.tank = FuelTank() + } + Type.GAS -> { + this.tank = GasTank() + } + } + this.tankMouth = TankMouth(fuelType, this.tank) + } +} + +/** + * Реализация бака с бензином + * @version = 1.0 + */ +class FuelTank: Tank { + override var level = 0 + var type = "Бак с бензином" +} + +/** + * Реализация бака с газом + * @version = 1.0 + */ +class GasTank: Tank{ + override var level = 0 + var type = "Бак с газом" +} + diff --git a/src/main/kotlin/ru/otus/cars/Taz.kt b/src/main/kotlin/ru/otus/cars/Taz.kt index 49df937..84a7718 100644 --- a/src/main/kotlin/ru/otus/cars/Taz.kt +++ b/src/main/kotlin/ru/otus/cars/Taz.kt @@ -36,4 +36,6 @@ object Taz: Car { override fun wheelToLeft(degrees: Int) { throw NotImplementedError("Руля нет") } + + override val fuelSystem: FuelSystem = FuelSystem(Type.GAS) } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/cars/Vaz2107.kt b/src/main/kotlin/ru/otus/cars/Vaz2107.kt index be857d2..fb85c24 100644 --- a/src/main/kotlin/ru/otus/cars/Vaz2107.kt +++ b/src/main/kotlin/ru/otus/cars/Vaz2107.kt @@ -20,6 +20,7 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) { override fun build(plates: Car.Plates): Vaz2107 = Vaz2107("Зеленый").apply { this.engine = getRandomEngine() this.plates = plates + this.fuelSystem = FuelSystem(Type.GAS) } /** @@ -39,7 +40,6 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) { // Переопределяем свойство родителя override lateinit var engine: VazEngine private set - /** * Семерка едет так */ @@ -59,7 +59,8 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) { // Выводим состояние машины override fun toString(): String { - return "Vaz2107(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed)" + return "Vaz2107(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed, " + + "fuelType=${fuelSystem.tankMouth.type}, fuelLevel=${fuelSystem.tankMouth.tank.level})" } /** @@ -67,6 +68,12 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) { */ override val carOutput: CarOutput = VazOutput() + /** + * Топливная система ВАЗ 2107 + */ + override lateinit var fuelSystem: FuelSystem + private set + /** * Имеет доступ к внутренним данным ЭТОГО ВАЗ-2107! */ @@ -74,5 +81,10 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) { override fun getCurrentSpeed(): Int { return this@Vaz2107.currentSpeed } + + override fun getFuelLevel(): Int { + return this@Vaz2107.fuelSystem.tankMouth.tank.level + } + } } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/cars/Vaz2108.kt b/src/main/kotlin/ru/otus/cars/Vaz2108.kt index 27b83b8..546b649 100644 --- a/src/main/kotlin/ru/otus/cars/Vaz2108.kt +++ b/src/main/kotlin/ru/otus/cars/Vaz2108.kt @@ -21,6 +21,7 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) { override fun build(plates: Car.Plates): Vaz2108 = Vaz2108("Красный").apply { this.engine = getRandomEngine() this.plates = plates + this.fuelSystem = FuelSystem(Type.FUEL) } fun alignWheels(vaz2108: Vaz2108) { @@ -63,13 +64,16 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) { // Выводим состояние машины override fun toString(): String { - return "Vaz2108(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed)" + return "Vaz2108(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed, " + + "fuelType=${fuelSystem.tankMouth.type}, fuelLevel=${fuelSystem.tankMouth.tank.level}" } /** * Делегируем приборы внутреннему классу */ override val carOutput: CarOutput = VazOutput() + override lateinit var fuelSystem: FuelSystem + private set /** * Имеет доступ к внутренним данным ЭТОГО ВАЗ-2108! @@ -78,5 +82,9 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) { override fun getCurrentSpeed(): Int { return this@Vaz2108.currentSpeed } + + override fun getFuelLevel(): Int { + return this@Vaz2108.fuelSystem.tankMouth.tank.level + } } } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/cars/main.kt b/src/main/kotlin/ru/otus/cars/main.kt index 978d0ef..959998d 100644 --- a/src/main/kotlin/ru/otus/cars/main.kt +++ b/src/main/kotlin/ru/otus/cars/main.kt @@ -1,5 +1,7 @@ package ru.otus.cars +import java.lang.Exception + fun main() { println("\n===> drive cars...") driveCars() @@ -16,6 +18,33 @@ fun main() { techChecks() println("\n===> Taz...") println(Taz.color) + + val car2107:Car = Vaz2107.build(Car.Plates("а007аа", 152)) + val car2108:Car = Vaz2108.build(Car.Plates("а008аа", 152)) + + val cars:List = mutableListOf(car2107, car2108) + + println("До заправки: $car2107") + println("Заправляем \"Сами\" на 10 литров") + car2107.fuelSystem.tankMouth.addFuel(10) + println("После заправки $car2107") + + println("До заправки: $car2108") + println("Заправляем \"Сами\" на 15 литров") + car2108.fuelSystem.tankMouth.addFuel(15) + println("После заправки $car2108") + + println("\nЗаправляемся на заправке:") + for(car in cars){ + try { + FuelStation.refuelCar(car, 10) + }catch (e:Exception){ + println("${car.toString()} не заправлена" ) + } + } + + //Taz.fuelSystem.tankMouth.addFuel(5) + } fun driveCars() { @@ -54,7 +83,7 @@ fun garageMake() { fun getEquipment() { val cars = listOf( - Vaz2107.build(Car.Plates("123", 77)), + Vaz2107.build(Car.Plates("123", 77), ), Vaz2108.build(Car.Plates("321", 78)) )