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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
- Дополнительное задание (не обязательно). Подумайте над архитектурой декоратора. Как можно сделать базовый класс декоратора для использования в разных
добавках без дублирования кода декорации.

## Задание 3. Профиль пользователя и делегирование
# Задание 3. Профиль пользователя и делегирование
В папке с домашним заданием вы [найдете](src/main/kotlin/ru/otus/homework/homework/UserProfile.kt) интерфейс профиля пользователя и его простую реализацию.
В этом задании вам предстоит сделать несколько доработок к классу реализации:

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'
}
}
12 changes: 6 additions & 6 deletions src/main/kotlin/ru/otus/homework/homework/Coffee.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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() + ", ваниль"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
73 changes: 71 additions & 2 deletions src/main/kotlin/ru/otus/homework/homework/UserProfile.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

package ru.otus.homework.homework

import kotlin.reflect.KProperty

/**
* Профиль пользователя
*/
Expand Down Expand Up @@ -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)
}
}
}
Expand All @@ -50,4 +52,71 @@ private val emailRegex = Regex("^[A-Za-z](.*)([@])(.+)(\\.)(.+)")
/**
* Реализация простого [UserProfile].
*/
private class ProfileImplementation(override var fullName: String, override var email: String): UserProfile
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<String>()
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<String> {
return log.toList()
}

}
8 changes: 6 additions & 2 deletions src/main/kotlin/ru/otus/homework/homework/processList.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@ inline fun processList(list: List<Int>, action: (Int) -> Unit) {
}
}


fun skipThreeAndPrint(list: List<Int>) {

// trailing lambda
processList(list) {
if (it == 3) return
println("Processing $it")
if (it == 3) return@processList
print("Processing $it\n")
}

}