Template Method Pattern

ν˜Έλ–‘Β·2022λ…„ 10μ›” 11일
0

πŸ’‘ Spring FrameWork νŒŒμƒ κ°œλ…


ν…œν”Œλ¦Ώ λ©”μ†Œλ“œ νŒ¨ν„΄ (Template Method Pattern)

μ „μ²΄μ μœΌλ‘œλŠ” λ™μΌν•˜λ©΄μ„œ λΆ€λΆ„μ μœΌλ‘œλŠ” λ‹€λ₯Έ ꡬ문으둜 κ΅¬μ„±λœ λ©”μ„œλ“œμ˜ μ½”λ“œ 쀑볡을 μ΅œμ†Œν™” ν•  λ•Œ μœ μš©ν•˜λ‹€.

λ³€μˆ˜(name)λ‚˜ ν•¨μˆ˜(doSomething( )) λ‹¨μœ„μ˜ 곡톡 뢀뢄은 상속을 톡해 쀑볡 μ œκ±°κ°€ κ°€λŠ₯ν•˜λ‹€. 이 λ•Œ ν•¨μˆ˜ λ‚΄μ˜ μ½”λ“œλ“€μ΄ μ„œλ‘œ λ‹€λ₯Έ κ²½μš°μ— λŒ€ν•΄μ„œλŠ” λΆ€λͺ¨ ν΄λž˜μŠ€μ—μ„œ abstract 처리λ₯Ό ν•¨μœΌλ‘œμ¨ Person 객체의 ꡬ쑰 μžμ²΄λŠ” μœ μ§€ν•˜λ©΄μ„œ κ°œλ³„ κ°μ²΄λ§ˆλ‹€ μ ν•©ν•œ ν•¨μˆ˜ λ‚΄λΆ€(doSomething( ))λ₯Ό κ΅¬ν˜„ν•  수 μžˆλ‹€.
μ—¬κΈ°μ„œ doSomething( ) λ‚΄λΆ€μ—μ„œ λͺ‡λͺ‡μ˜ 곡톡 뢀뢄을 μ²˜λ¦¬ν•¨μœΌλ‘œμ¨ 곡톡 ꡬ쑰λ₯Ό λ§Œλ“€μ–΄λ‚Έ 것이 ν…œν”Œλ¦Ώ λ©”μ†Œλ“œ νŒ¨ν„΄μ΄λ‹€.

πŸ‘‰ μ–΄λ–€ ν•˜λ‚˜μ˜ ν…œν”Œλ¦Ώ λ©”μ†Œλ“œ μ•ˆμ—μ„œ 좔상 λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν•˜κ³ , 좔상 λ©”μ„œλ“œμ˜ ꡬ체적인 
λ™μž‘μ€ μžμ‹ν΄λž˜μŠ€μ—μ„œ ꡬ체적으둜 κ΅¬ν˜„ν•  수 μžˆλ„λ‘ ν•œλ‹€.

예제

상속은 λ³€μˆ˜μ™€ ν•¨μˆ˜ λ‹¨μœ„λ₯Ό λΆ€λͺ¨λ‘œ λ¬Άμ–΄λ‚΄λŠ” 방법이라면, ν…œν”Œλ¦Ώ λ©”μ†Œλ“œ νŒ¨ν„΄μ€ μ½”λ“œ λ‹¨μœ„μ˜ 곡톡 ꡬ쑰λ₯Ό ν•˜λ‚˜λ‘œ λ¬Άμ–΄λ‚΄λŠ” 방법이닀.

λΆ€λͺ¨ ν΄λž˜μŠ€μ—μ„œ 곡톡 λ³€μˆ˜μ™€ ν•¨μˆ˜λ‘œ Person ꡬ쑰λ₯Ό λ§Œλ“ λ‹€.


public abstract class Person {
	private String name;
	
    // μžμ‹ ν΄λž˜μŠ€μ—μ„œ κ°œλ³„ 객체에 맞게 κ΅¬ν˜„ν•  λΆ€λΆ„
	public abstract void doSomething();
	
    // ν…œν”Œλ¦Ώ λ©”μ†Œλ“œ μ•ˆμ—μ„œ 좔상 λ©”μ„œλ“œλ₯Ό 호좜
    // 동적 바인딩에 μ˜ν•΄ μžμ‹ ν΄λž˜μŠ€μ—μ„œ ꡬ체적으둜 κ΅¬ν˜„ν•œ doSomething()이 호좜
	public void daily() {
		System.out.println("μž…μ‹€μ²΄ν¬ν•œλ‹€.");
		doSomething();
		System.out.println("ν‡΄μ‹€μ²΄ν¬ν•œλ‹€.");
	}
}

μžμ‹ν΄λž˜μŠ€1. Employee


public class Employee extends Person{

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("μ†Œμ™€ 같이 일을 ν•œλ‹€.");
		System.out.println("μ›°μŠ€ν† λ¦¬λ₯Ό λ¨ΉλŠ”λ‹€.");
	}

}

μžμ‹ν΄λž˜μŠ€2. Student


public class Student extends Person{

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("κ³΅λΆ€ν•œλ‹€.");
		System.out.println("급식을 λ¨ΉλŠ”λ‹€.");
	}

}

0개의 λŒ“κΈ€