diff --git a/README.md b/README.md index 57f0db2..240be80 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ - Дополнительное задание (не обязательно). Подумайте над архитектурой декоратора. Как можно сделать базовый класс декоратора для использования в разных добавках без дублирования кода декорации. -## Задание 3. Профиль пользователя и делегирование +# Задание 3. Профиль пользователя и делегирование В папке с домашним заданием вы [найдете](src/main/kotlin/ru/otus/homework/homework/UserProfile.kt) интерфейс профиля пользователя и его простую реализацию. В этом задании вам предстоит сделать несколько доработок к классу реализации: 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/homework/homework/Coffee.kt b/src/main/kotlin/ru/otus/homework/homework/Coffee.kt index c73f420..aa6316c 100644 --- a/src/main/kotlin/ru/otus/homework/homework/Coffee.kt +++ b/src/main/kotlin/ru/otus/homework/homework/Coffee.kt @@ -22,30 +22,30 @@ class SimpleCoffee : Coffee { class MilkDecorator(private val coffee: Coffee) : Coffee { override fun cost(): Int { - TODO("Not yet implemented") + return coffee.cost() + 50 } override fun description(): String { - TODO("Not yet implemented") + return coffee.description() + ", молоко" } } class SugarDecorator(private val coffee: Coffee) : Coffee { override fun cost(): Int { - TODO("Not yet implemented") + return coffee.cost() + 20 } override fun description(): String { - TODO("Not yet implemented") + return coffee.description() + ", сахар" } } class VanillaDecorator(private val coffee: Coffee) : Coffee { override fun cost(): Int { - TODO("Not yet implemented") + return coffee.cost() + 70 } override fun description(): String { - TODO("Not yet implemented") + return coffee.description() + ", ваниль" } } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt b/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt index 568f368..dbeddd2 100644 --- a/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt +++ b/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt @@ -6,11 +6,14 @@ import kotlin.reflect.KProperty * Delegate that allows to set non-empty string value */ class NonEmptyStringDelegate() { + private var value:String = "" operator fun getValue(thisRef: Any?, property: KProperty<*>): String { - TODO("Implement `getValue` function") + return value } operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String) { - TODO("Implement `setValue` function") + if(newValue.isNotBlank()){ + value = newValue + } } } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt b/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt index f0fab82..201e1f4 100644 --- a/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt +++ b/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt @@ -2,6 +2,8 @@ package ru.otus.homework.homework +import kotlin.reflect.KProperty + /** * Профиль пользователя */ @@ -37,7 +39,7 @@ interface UserProfile { * Creates user profile with logging */ fun createWithLogging(fullName: String, email: String): UserProfile.Logging { - TODO("Implement `createWithLogging` function") + return ProfileLogImpl(fullName, email) } } } @@ -50,4 +52,71 @@ private val emailRegex = Regex("^[A-Za-z](.*)([@])(.+)(\\.)(.+)") /** * Реализация простого [UserProfile]. */ -private class ProfileImplementation(override var fullName: String, override var email: String): UserProfile \ No newline at end of file +private class ProfileImplementation(propFullName: String, propEmail: String): UserProfile{ + override var fullName: String by FullNameValidator(propFullName)// Использовать NonEmptyStringDelegate() для NonEmptyStringDelegateTest + override var email: String by EmailValidator(propEmail) +} + +private class FullNameValidator(private var fullName: String){ + /* + Геттер поля fullName + */ + operator fun getValue(thisRef: UserProfile, property: KProperty<*>): String { + return fullName + } + + /* + Сеттер поля fullName. Если fullName пустой - не устанавливаем значение и не бросаем Exception + */ + operator fun setValue(thisRef: UserProfile, property: KProperty<*>, fullNameValue:String ){ + if( fullNameValue.isNotBlank() ) { + fullName = fullNameValue + } + } +} +private class EmailValidator(private var email: String){ + /* + Геттер поля email + */ + operator fun getValue(thisRef: UserProfile, property: KProperty<*>): String { + return email + } + + /* + Сеттер поля email. Если email кривой - не устанавливаем значение и не бросаем Exception + */ + operator fun setValue(thisRef: UserProfile, property: KProperty<*>, emailValue:String ){ + if( emailRegex.matches(emailValue) ) { + email = emailValue + return + } + } + +} + + +private class ProfileLogImpl(userName:String, email:String): UserProfile.Logging { + private var userProfile: UserProfile = ProfileImplementation(userName, email) + private var log = mutableListOf() + override var fullName: String + get() = userProfile.fullName + set(value) { + if(value != userProfile.fullName){ + log.add("Changing `fullName` from '${userProfile.fullName}' to '$value'") + userProfile.fullName = value + } + } + override var email: String + get() = userProfile.email + set(value) { + if(value != userProfile.email){ + log.add("Changing `email` from '${userProfile.email}' to '$value'") + userProfile.email = value + } + } + + override fun getLog(): List { + return log.toList() + } + +} \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/homework/processList.kt b/src/main/kotlin/ru/otus/homework/homework/processList.kt index 6d8ab43..fb0d08b 100644 --- a/src/main/kotlin/ru/otus/homework/homework/processList.kt +++ b/src/main/kotlin/ru/otus/homework/homework/processList.kt @@ -6,9 +6,13 @@ inline fun processList(list: List, action: (Int) -> Unit) { } } + fun skipThreeAndPrint(list: List) { + + // trailing lambda processList(list) { - if (it == 3) return - println("Processing $it") + if (it == 3) return@processList + print("Processing $it\n") } + }