2023. 3. 6. 16:39ใJAVA/Effective JAVA
item20. ์ถ์ํด๋์ค๋ณด๋ค ์ธํฐํ์ด์ค๋ฅผ ์ฐ์ ํ๋ผ.
" p.132 ํ ํ๋ฆฟ ๋ฉ์๋ ํจํด"
๐ ํ ํ๋ฆฟ ๋ฉ์๋ ํจํด์ด๋?
: ์๊ณ ๋ฆฌ์ฆ ๊ตฌ์กฐ๋ฅผ ์๋ธ ํด๋์ค๊ฐ ํ์ฅํ ์ ์๋๋ก ํ ํ๋ฆฟ์ผ๋ก ์ ๊ณตํ๋ ๋ฐฉ๋ฒ
์ ์ฒด์ ์ผ๋ก๋ ๋์ผํ๋ฐ ๋ถ๋ถ์ ์ผ๋ก ๋ค๋ฅธ ๋ถ๋ถ์ ๋ฐ๋ก ํ์ฅํด์ ์์ฑํ ์ ์๋๋ก ๋์์ฃผ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ฝ๋ ์ค๋ณต์ ์ต์ํํ ์ ์๋ค!
public abstract class FileProcessor
{
private String path;
public FileProcessor(String path)
{
this.path = path;
}
// templateMethod()
public final int process()
{
try(BufferedReader reader = new BufferedReader(new FileReader(path)))
{
int result = 0;
String line = null;
while((line = reader.readLine()) != null)
{
result = getResult(result, Integer.parseInt(line));
}
return result;
}
catch (IOException e)
{
throw new IllegalArgumentException(path + "์ ํด๋นํ๋ ํ์ผ์ด ์์ต๋๋ค.", e);
}
}
// step1()
protected abstract int getResult(int result, int parseInt);
}
process ๋ฉ์๋๊ฐ ์์ ๊ทธ๋ฆผ์์ templatemethod์ ํด๋นํ๊ณ getResult()๊ฐ ์ด์ ๊ฐ๊ฐ ํ์ฅํด์ ์ฌ์ฉํ ์ ์๋ ๋ถ๋ถ์ผ๋ก step1์ ํด๋นํ๋ค.
public class Plus extends FileProcessor
{
public Plus(String path)
{
super(path);
}
@Override
protected int getResult(int result, int parseInt)
{
return result + parseInt;
}
}
FileProcessor๋ฅผ ์์๋ฐ์์ getResult๋ฅผ ๊ตฌํํด์ฃผ๋ฉด ๋๋ค.
public static void main(String[] args)
{
FileProcessor fileProcessor = new Plus("number.txt");
System.out.println(fileProcessor.process());
}
๊ทผ๋ฐ ์ฌ๊ธฐ์ ์ด์ ์์์ ์ฌ์ฉํ์ง ์๊ณ ๋ ํ ์ ์๋ ๋ฐฉ๋ฒ์ผ๋ก ํ ํ๋ฆฟ ์ฝ๋ฐฑ ํจํด์ด ์๋ค.
๐ ํ ํ๋ฆฟ ์ฝ๋ฐฑ ํจํด์ด๋?
๊ตฌ์ฒดํด๋์ค๋ฅผ ๋ง๋ค์ง ์๊ณ ์ต๋ช ๋ด๋ถ ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ผ๋ก
public class CallbackFileProcessor
{
private String path;
public CallbackFileProcessor(String path)
{
this.path = path;
}
public final int process(BiFunction<Integer, Integer, Integer> operator)
{
try(BufferedReader reader = new BufferedReader(new FileReader(path)))
{
int result = 0;
String line = null;
while((line = reader.readLine()) != null)
{
result = operator.apply(result, Integer.parseInt(line));
}
return result;
}
catch (IOException e)
{
throw new IllegalArgumentException(path + "์ ํด๋นํ๋ ํ์ผ์ด ์์ต๋๋ค.", e);
}
}
}
public static void main(String[] args)
{
FileProcessor fileProcessor = new Plus("number.txt");
System.out.println(fileProcessor.process());
CallbackFileProcessor callbackFileProcessor = new CallbackFileProcessor("number.txt");
int result = callbackFileProcessor.process((a, b) -> a + b);
System.out.println("result = " + result);
}
ํด๋ผ์ด์ธํธ๋จ์์ ์ต๋ช ํด๋์ค๋ฅผ ํตํด ์ ๋ต์ ๊ทธ๋ ๊ทธ๋ ์ ํด์ฃผ๋ฉด์ ๋ก์ง์ ์ํํ ์ ์๋ค!!
ํ ํ๋ฆฟ ์ฝ๋ฐฑ ํจํด์ ์คํ๋ง ์ฌ์ฉํ ๋ ์ฃผ๋ก ๋ณผ ์ ์๋ ํจํด์ด๋ค.