diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..f1ad17c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ + +# Created by .ignore support plugin (hsz.mobi) +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +.DS_Store +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar +/out/ +/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr \ No newline at end of file diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/build.gradle" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/build.gradle" new file mode 100644 index 00000000..95687b5b --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/build.gradle" @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/gradlew" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/gradlew" new file mode 100644 index 00000000..4f906e0c --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/gradlew" @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/gradlew.bat" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/gradlew.bat" new file mode 100644 index 00000000..107acd32 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/gradlew.bat" @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/Application.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/Application.java" new file mode 100644 index 00000000..c9af397f --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/Application.java" @@ -0,0 +1,8 @@ +import utils.GameUtils; + +public class Application { + public static void main(String[] args) { + GameUtils gameUtils = new GameUtils(); + gameUtils.run(); + } +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/inpututils/InputView.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/inpututils/InputView.java" new file mode 100644 index 00000000..734dca32 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/inpututils/InputView.java" @@ -0,0 +1,21 @@ +package inpututils; + +import java.util.Scanner; + +public class InputView { + private static final Scanner SCANNER = new Scanner(System.in); + + public static String getCarName() { + System.out.print("경주 할 자동차 이름 : "); + return SCANNER.nextLine(); + } + + public static int getTryNumber() { + System.out.print("시도할 횟수 : "); + try { + return SCANNER.nextInt(); + } catch (NumberFormatException e) { + throw new NumberFormatException("[ERROR] 시도 횟수는 숫자여야 한다."); + } + } +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/outpututils/OutputView.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/outpututils/OutputView.java" new file mode 100644 index 00000000..a8e5a7d7 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/outpututils/OutputView.java" @@ -0,0 +1,22 @@ +package outpututils; + +import java.util.ArrayList; + +public class OutputView { + private OutputView() { + } + + public static void printCarName(String name) { + System.out.print(name + " : "); + } + + public static void printMove() { + System.out.print("-"); + } + + public static void printWinner(ArrayList winner) { + //TODO:마지막에 , 나오지 않도록 수정 필요 + winner.stream() + .forEach(w -> System.out.print(w + ",")); + } +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/racingcar/Car.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/racingcar/Car.java" new file mode 100644 index 00000000..ffdd75df --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/racingcar/Car.java" @@ -0,0 +1,25 @@ +package racingcar; + +import utils.GameUtils; + +public class Car { + private final String name; + private int position = 0; + + public Car(String name) { + this.name = name; + } + + public String getName(){ + return name; + } + + public int plusPosition(){ + return position++; + } + + public int getPosition() { + return position; + } + +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/racingcar/Cars.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/racingcar/Cars.java" new file mode 100644 index 00000000..e070bb54 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/racingcar/Cars.java" @@ -0,0 +1,62 @@ +package racingcar; + +import outpututils.OutputView; +import utils.RandomUtils; +import java.util.ArrayList; +import java.util.List; + +public class Cars { + private static List carList; + + private static final int START_NUMBER = 0; + private static final int END_NUMBER = 9; + + private static final int BOUNDARY_NUMBER = 4; + + private static ArrayList winner; + + public Cars(List carList) { + this.carList = carList; + } + + public static boolean isMove(int randomNumber) { + if (randomNumber >= BOUNDARY_NUMBER) { + return true; + } + return false; + } + + public static void playGame() { + for (int j = 0; j < carList.size(); j++) { + OutputView.printCarName(carList.get(j).getName()); + + if (isMove(RandomUtils.nextInt(START_NUMBER, END_NUMBER))) { + carList.get(j).plusPosition(); + } + for (int k = 0; k < carList.get(j).getPosition(); k++) { + OutputView.printMove(); + } + System.out.println(); + } + } + + public static int getMax() { + int max = carList.stream() + .mapToInt(Car::getPosition) + .max() + .getAsInt(); + return max; + } + + public static void setWinnerList(int max) { + winner = new ArrayList(); + carList.stream() + .filter(s-> s.getPosition()==max) + .filter(s-> winner.add(s.getName())) + .collect(Collectors.toList()); + } + public static ArrayList getWinnerList() { + return winner; + } + +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/GameUtils.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/GameUtils.java" new file mode 100644 index 00000000..1a1f0fa5 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/GameUtils.java" @@ -0,0 +1,35 @@ +package utils; + +import inpututils.InputView; +import outpututils.OutputView; +import racingcar.Car; +import racingcar.Cars; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class GameUtils { + + public static List makeCarList(String[] splitResult) { + return Arrays.stream(splitResult) + .map(Car::new) + .collect(Collectors.toList()); + } + + public static void run() { + String inputName = InputView.getCarName(); + int inputCount = InputView.getTryNumber(); + String[] splitResult = SplitString.splitString(inputName); + + Cars cars = new Cars(makeCarList(splitResult)); + + for (int i = 0; i < inputCount; i++) { + Cars.playGame(); + System.out.println(); + } + + Cars.setWinnerList(Cars.getMax()); + OutputView.printWinner(Cars.getWinnerList()); + } +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/RandomUtils.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/RandomUtils.java" new file mode 100644 index 00000000..020c8f40 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/RandomUtils.java" @@ -0,0 +1,24 @@ +package utils; + +import java.util.Random; + +public class RandomUtils { + private static final Random RANDOM = new Random(); + + private RandomUtils() { + } + + public static int nextInt(final int startInclusive, final int endInclusive) { + if (startInclusive > endInclusive) { + throw new IllegalArgumentException(); + } + if (startInclusive < 0) { + throw new IllegalArgumentException(); + } + + if (startInclusive == endInclusive) { + return startInclusive; + } + return RANDOM.nextInt(endInclusive - startInclusive + 1) + startInclusive; + } +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/SplitString.java" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/SplitString.java" new file mode 100644 index 00000000..d91bb318 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/java/utils/SplitString.java" @@ -0,0 +1,10 @@ +package utils; + +public class SplitString { + private SplitString() { + } + + public static String[] splitString(String input) { + return input.split(","); + } +} diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/settings.gradle" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/settings.gradle" new file mode 100644 index 00000000..563821bb --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/RacingCar/settings.gradle" @@ -0,0 +1,2 @@ +rootProject.name = 'racingcar' + diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/\354\236\220\353\260\224 \354\212\244\355\212\270\353\246\274(Stream).md" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/\354\236\220\353\260\224 \354\212\244\355\212\270\353\246\274(Stream).md" new file mode 100644 index 00000000..5040ed09 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/\354\236\220\353\260\224 \354\212\244\355\212\270\353\246\274(Stream).md" @@ -0,0 +1,131 @@ +# 자바 스트림(Stream) 정리 + +## 스트림(Stream)이란? +> 자바 8부터 추가된 컬렉션의 저장 요소를 하나씩 참조해 람다식으로 처리할 수 있도록 해주는 반복자 +> Iterator과 비슷한 역할을 하지만 람다식을 이용해 코드가 좀 더 간결할 수 있다. + +1. 생성하기: 스트림 인스턴스 생성 +2. 가공하기: 필터링 및 맵핑 등 원하는 결과를 만들어가는 과정 +3. 결과 만들기: 최종적으로 결과를 만들어내는 작업 + +## 생성하기 + +### 배열 스트림 +Arrays.stream 메소드를 이용 +``` +String[] strArr = new String[]{"김가나", "이다라", "박마바"}; +Stream stream = Arrays.stream(strArr); +Stream streamOfArrayPart = + Arrays.stream(strArr, 1, 3); // 1~2 요소 ["이다라", "박마바"] +``` +### 컬렉션 스트림 +컬렉션 타입(Collection,List,Set) 은 stream 이용 +``` +public interface Collection extends Iterable { + default Stream stream() { + return StreamSupport.stream(spliterator(), false); + } + // ... +} +``` +다음과 같이 생성 +``` +List list = Arrays.asList("a", "b", "c"); +Stream stream = list.stream(); +Stream parallelStream = list.parallelStream(); // 병렬 처리 스트림 +``` + +### Stream.builder() +스트림에 직접 원하는 값을 넣을 수 있고, build 메소드로 스트림을 리턴 +``` +Stream builderStream = + Stream.builder() + .add("AB").add("CC").add("JJ") + .build(); // [AB, CC, JJ] +``` + +### Stream.generate() +Supplier에 해당하는 람다로 값을 넣을 수 있다. Supplier는 인자는 없고 리턴값만 있는 함수형 인터페이스 +``` +public static Stream generate(Supplier s) { ... } +``` +이때 생성되는 스트림은 크기가 정해져있지 않기 때문에 특정 사이즈로 크기 제한 해야한다. +``` +Stream generatedStream = + Stream.generate(() -> "gen").limit(5); // [el, el, el, el, el] +``` + +## 가공하기 +스트림을 리턴하기 때문에 여러 작업을 이어 붙여 작성 가능 +``` +List names = Arrays.asList("Eric", "Elena", "Java"); +``` +위의 리스트를 대상으로 예제 코드를 작성 + +### Filtering +``` +Stream filter(Predicate predicate); +``` +``` +Stream stream = + names.stream() + .filter(name -> name.contains("a")); +// [Elena, Java] +// 'a' 가 들어간 이름만 스트림 리턴됨 +``` + +### Mapping +``` + Stream map(Function mapper); +``` + +``` +Stream stream = + names.stream() + .map(String::toUpperCase); +// [ERIC, ELENA, JAVA] +``` +toUpperCase로 대문자로 변환된 값들이 담긴 스트림 리턴 + +``` +Stream stream = + productList.stream() + .map(Product::getAmount); +// [23, 14, 13, 23, 13] +``` +Product 개체의 수량을 꺼내올 수 있다 + +## 결과 만들기 +가공한 스트림으로 내가 사용할 결과값을 만들어내는 단계이다. + +### Calculating +``` +long count = IntStream.of(1, 3, 5, 7, 9).count(); +long sum = LongStream.of(1, 3, 5, 7, 9).sum(); +``` +min(),max()와 같은 것도 가능 + +### Collecting +collect 메소드는 또 다른 종료 작업으로, Collector 타입의 인자를 받아 처리함 +``` +List productList = + Arrays.asList(new Product(23, "potatoes"), + new Product(14, "orange"), + new Product(13, "lemon"), + new Product(23, "bread"), + new Product(13, "sugar")); +``` +다음 예제에는 이 Product 객체를 사용 + +### Collectors.toList() +스트림에서 작업한 결과를 담은 리스트로 반환한다. +``` +List collectorCollection = + productList.stream() + .map(Product::getName) + .collect(Collectors.toList()); +// [potatoes, orange, lemon, bread, sugar] + +``` + +[출처, 더 많은 내용 참고](https://futurecreator.github.io/2018/08/26/java-8-streams/) \ No newline at end of file diff --git "a/8\354\243\274\354\260\250\352\263\274\354\240\234/\354\236\220\353\260\224\352\270\260\354\264\210.md" "b/8\354\243\274\354\260\250\352\263\274\354\240\234/\354\236\220\353\260\224\352\270\260\354\264\210.md" new file mode 100644 index 00000000..ec17b2c4 --- /dev/null +++ "b/8\354\243\274\354\260\250\352\263\274\354\240\234/\354\236\220\353\260\224\352\270\260\354\264\210.md" @@ -0,0 +1,216 @@ +# 2021-java-study +2021 자바 스터디 8주차 과제 + +# 자바 기초 + +## CQRS +> CQRS는 Command and Query Responsibility Segregation의 약자로, 명령과 조희의 책임 분리를 의미한다. +>
즉, 시스템의 상태를 변경하는 작업과 시스템의 상태를 반환하는 작업의 책임을 분리 하는 것이다. +> + +### CQRS의 예시 - API 응용 프로그램 + +### CQRS 적용 전 API + +사용자를 등록하는 API 코드 +``` +[ResponseType(typeof(UserPresentation))] +public async Task Post(CreateUser command) +{ + UserPresentation user = await _domainLayer.CreateUserAsync(command); + return CreatedAtRoute("DefaultApi", new { id = user.Id }, user); +} +``` +http 요청을 통해 CreateUser 명령을 입력받아 도메인 계층에 전달하고 명령이 완료되면 Created 응답을 반환한다. +응답에는 생성된 자원의 위치를 나타내는 location 헤더와 생성된 사용자 엔터티에 대한 본문이 포함된다. +이 동작을 지원하기 위해 도메인 계층의 CreateUserAsync() 메서드는 명령 실행 후 UserPresentation 개체를 반환한다. + +
+ +도메인 계층의 CreateUserAsync() 메소드 코드 +``` +public async Task CreateUserAsync(CreateUser command) +{ + int userId = await _repository.InsertAsync(new User + { + UserName = command.UserName, + PasswordHash = _passwordHasher.HashPassword(command.Password) + }); + + User user = await _repository.FindAsync(userId); + + return new UserPresentation + { + Id = user.Id, + UserName = user.UserName + }; +} +``` +이 메소드는 크게 두가지 작업을 수행한다. +첫번째는 CreateUser 명령에 들어있는 정보를 사용해 새 사용자 엔터티를 생성하는 것다. +두번째는 생성된 사용자 엔터티를 조회해 표현 계층 모델로 변환해 반환하는 것이다. +영속 모델(User) 개체를 그대로 반환하면 PasswordHash 속성이 서비스 외부로 노출되는 보안 문제가 발생한다. + +### CQRS 적용 후 API +사용자 엔터티 조회 작업을 읽기 모델로 분리하고, API 계층이 응답 본문 작성을 위해 분리된 읽기 모델을 사용하도록 수정하면 UsersDomainModel.CreateUserAsync() 메서드는 더이상 값을 반환할 필요가 없으며 새 엔터티 생성에 대한 책임만 가진다. + +``` +public async Task CreateUserAsync(CreateUser command) +{ + await _repository.InsertAsync(new User + { + Id = command.UserId, + UserName = command.UserName, + PasswordHash = _passwordHasher.HashPassword(command.Password) + }); +} +``` +User 엔터티를 저장하기 전에 식별자(Id)를 지정한다는 것이다. +그리고 이 식별자는 CreateUser 명령을 통해 전달된다. +즉 CreateUserAsync() 메서드가 호출되기 전에 식별자가 정해진다. +이 조건을 만족하기 위해 엔터티 식별자 형식을 Guid로 변경한다. +Guid를 식별자 형식으로 사용하면 엔터티가 데이터 저장소에 영속되기 전에 식별자를 결정하면서도 기존 엔터티의 식별자와 중복되지 않음을 보장할 수 있다. +CQRS에서는 일반적으로 Guid를 엔터티 식별자로 사용한다. + +### CQRS의 장점 +- 각각 도메인 목적에 맞게 개발 할 수 있다. +- 명령과 쿼리 파이프라인을 원하는대로 최적화 하며 다른 요소가 깨질 위험이 거의 없다. + +### CQRS의 단점 +- 구현해야 할 코드가 많아진다. +- 더 많은 구현 기술이 필요해진다. +- 유지 비용이 증가한다. + +## 디미터 법칙 +> Object-Oriented Programming:An Objective Sense of Style 에서 처음 소개된 개념 +>
객체 간 관계를 설정할 때 객체 간의 결합도를 효과적으로 낮출 수 있다. +>
객체 구조의 경로를 따라 멀리 떨어져 있는 낯선 객체에 메시지를 보내는 설계를 피하라는 것이다. +>
Don't Talk to Strangers + +``` +public class Post { + private final List comments; + + public Post(List comments) { + this.comments = comments; + } + + public List getComments() { + return comments; + } +} +``` +``` +public class Board { + private final List posts; + + public Board(List posts) { + this.posts = posts; + } + + public void addComment(int postId, String content) { + posts.get(postId).getComments().add(new Comment(content)); + } + ... +} +``` +addComment 메소드를 보면 Board 객체의 인스턴스 변수 posts 에서 getter를 거듭하여 객체 Comment를 추가하는 코드이다. +이렇게 getter가 계속 이어지는 코드는 디미터 법칙을 위반하는 코드이다. + +만약 Post객체에서 인스턴스 변수가 List comments에서 Comments라는 일급컬렉션 객체로 수정된다면 getter을 통해 List comments를 사용하던 Board 객체의 addComment 메서드가 깨지게 된다. + +디미터 법칙에서는 노출 범위를 제한하기 위해 +- 객체 자신의 메소드를 +- 메소드의 파라미터로 넘어온 객체들의 메소드들 +- 메소드 내부에서 생성, 초기화 된 객체의 메소드들 +- 인스턴스 변수로 가지고 있는 객체가 소유한 메소드들 + +에 해당하는 메소드를 호출해야 한다고 한다. + +``` +class Demeter { + private Member member; + + public myMethod(OtherObject other) { + // ... + } + + public okLawOfDemeter(Paramemter param) { + myMethod(); // 1. 객체 자신의 메서드 + param.paramMethod(); // 2. 메서드의 파라미터로 넘어온 객체들의 메서드 + Local local = new Local(); + local.localMethod(); // 3. 메서드 내부에서 생성, 초기화된 객체의 메서드 + member.memberMethod(); // 4. 인스턴스 변수로 가지고 있는 객체가 소유한 메서드 + } +} +``` + +## 일급 컬렉션 +> 콜렉션을 Wrapping 하면서, 그 외 다른 멤버 변수가 없는 상태 + +이 코드를 +``` +Map map = new HashMap<>(); +map.put("1", "A"); +map.put("2", "B"); +map.put("3", "C"); +``` +아래와 같이 wrapping 하는 것 +``` +public class GameRanking { + + private Map ranks; + + public GameRanking(Map ranks) { + this.ranks = ranks; + } +} +``` + +다른 예시 +``` +public class Car { + private int position; + + public void move(MovingStrategy movingStrategy){ + if(movingStrategy.isMove()){ + position++; + } + } + + public int getPosition() { + return position; + } +} +``` +``` +Car a = new Car(); +Car b = new Car(); +Car c = new Car(); +``` + +일급컬렉션인 Cars 클래스로 함께 관리 +``` +public class Cars{ + + private List cars; + + public Cars(List cars){ + this.cars=this.cars; + } + + public List getCars(){ + return cars; + } + +} +``` + +### 일급 컬렉션의 이점 +1. 비지니스에 종속적인 자료구조 +2. Collection의 불변성을 보장 +3. 상태와 행위를 한 곳에서 관리 +4. 이름이 있는 컬렉션 + + +