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
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 16 additions & 7 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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'
}
}
5 changes: 5 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,11 @@ interface Car : CarInput {
*/
val carOutput: CarOutput

/**
* Топливная система авто
*/
val fuelSystem:FuelSystem

/**
* Получить оборудование
*/
Expand Down
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 getFuelLevel(): Int
}
41 changes: 41 additions & 0 deletions src/main/kotlin/ru/otus/cars/FuelStation.kt
Original file line number Diff line number Diff line change
@@ -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){
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mahonin-ms, получился костыль в заправке. Почему бы не сделать взрыв непосредственно в ТАЗу? Зачем другим компонентам знать "детали его внутренней реализации"?

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)
}

}

}
62 changes: 62 additions & 0 deletions src/main/kotlin/ru/otus/cars/FuelSystem.kt
Original file line number Diff line number Diff line change
@@ -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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mahonin-ms идея объединить бак и горловину единой внешней сущностью - это хорошее решение! Но ссылка к машине, опять же, кажется лишней. В реальной жизни топливную систему в сборе ставят в машину. Горловина торчит наружу - это и есть интерфейс для заправки

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 = "Бак с газом"
}

2 changes: 2 additions & 0 deletions src/main/kotlin/ru/otus/cars/Taz.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,6 @@ object Taz: Car {
override fun wheelToLeft(degrees: Int) {
throw NotImplementedError("Руля нет")
}

override val fuelSystem: FuelSystem = FuelSystem(Type.GAS)
}
16 changes: 14 additions & 2 deletions src/main/kotlin/ru/otus/cars/Vaz2107.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

/**
Expand All @@ -39,7 +40,6 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) {
// Переопределяем свойство родителя
override lateinit var engine: VazEngine
private set

/**
* Семерка едет так
*/
Expand All @@ -59,20 +59,32 @@ 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})"
}

/**
* Делегируем приборы внутреннему классу
*/
override val carOutput: CarOutput = VazOutput()

/**
* Топливная система ВАЗ 2107
*/
override lateinit var fuelSystem: FuelSystem
private set

/**
* Имеет доступ к внутренним данным ЭТОГО ВАЗ-2107!
*/
inner class VazOutput : CarOutput {
override fun getCurrentSpeed(): Int {
return [email protected]
}

override fun getFuelLevel(): Int {
return [email protected]
}

}
}
10 changes: 9 additions & 1 deletion src/main/kotlin/ru/otus/cars/Vaz2108.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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!
Expand All @@ -78,5 +82,9 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) {
override fun getCurrentSpeed(): Int {
return [email protected]
}

override fun getFuelLevel(): Int {
return [email protected]
}
}
}
31 changes: 30 additions & 1 deletion src/main/kotlin/ru/otus/cars/main.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.otus.cars

import java.lang.Exception

fun main() {
println("\n===> drive cars...")
driveCars()
Expand All @@ -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<Car> = 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() {
Expand Down Expand Up @@ -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))
)

Expand Down