본문 바로가기
Today I learned

재사용 가능한 디자인 패턴 기반 코딩기술 강의 정리 - Delegation

by soheemon 2021. 8. 2.

 

Pattern In Java에서 소개하는 디자인패턴은 GoF보다 비교적 간단하다.

GoF에서의 디자인 패턴은 보다 큰 규모의 프로젝트에서 사용할수 있을것 같은데, PiJ에 있는 패턴은 지금 알게 모르게 사용중이거나, 바로 업무에 적용할 수 있을정도의 소소한 패턴들이다.

하지만 강의에서는 이런 소소한 패턴들을 확장시켜 나가면 결국 GoF처럼 규모있는 패턴으로 발전하게 된다고 한다.

 

Delegation

위임

Problem

A클래스에서 B클래스의 메서드를 사용할 수 있는 방법은 어떤것이 있을까? 가장 쉽게 떠올릴 수 있는게 상속이겠지.

아래의 예시를 보자.

엄마, 개발자, 아내, 국민은 각각의 doJob() 메서드를 가진다. 그리고 각자 자기의 일을 한다.

public class Person {
	private int age;
	private String name;
}

class Mother extends Person{
	public void doMotherJobs(){
		/*
		 * 1)엄마의 일을 하는 로직
		 */
	};
}

class MotherAndWife extends Person{
	public void doMotherAndWifeJobs(){
		/*
		 * 1)엄마의 일을 하는 로직
		 * 2)아내의 일을 하는 로직
		 */
	};
}

class MotherAndWifeAndDevelopment extends Person{
	public void doMotherAndWifeAndDevelopmentJobs(){
		/*
		 * 1)엄마의 일을 하는 로직
		 * 2)아내의 일을 하는 로직
		 * 3)개발자의 일을 하는 로직
		 */
	};	//역할이 늘어나고, 해야할일이 늘어난다고 해서 동일한 로직이 계속해서 추가될 필요가 있을까?

만약 한나라의 국민이자 엄마이고, 개발자이고, 아내의 일을 하는 메서드는 어떻게 구현할것인가?

메서드가 늘어날때마다 중복코드를 계속해서 발생시킬것인가?

Solution

예제가 지루하고 와닿지않고 어려운데 사실 답은 간단하다(...) 그리고 우리가 무의식적으로 이미 사용하고있다!

바로.. Class Attribute에 역할을 대신 해 줄 클래스를 선언하는것이다.

그리고 메서드 내부에서 역할을 대신해줄 클래스의 메서드를 호출한다!

 

public class Person {
	private int age;
	private String name;
}

class Mother extends Person{
	public void doMotherJobs(){
		/*
		 * 1)엄마의 일을 하는 로직
		 */
	};
}

class Developer extends Person{
	public void doDeveloperJobs(){

	};
}
class Wife extends Person{
	public void doWifeJobs(){

	};
}

class MotherAndWife extends Person{
	Mother mother = new Mother();
	Wife wife = new Wife();
	public void doMotherAndWifeJobs(){
		mother.doMotherJobs();
		wife.doWifeJobs();

	};
}

class MotherAndWifeAndDevelopment extends Person{
	MotherAndWife maw = new MotherAndWife();
	Developer dev = new Developer();
	public void doMotherAndWifeAndDevelopmentJobs(){
		maw.doMotherAndWifeJobs();
		dev.doDeveloperJobs();
	};
}

 

어디서 많이 본 패턴같지 않나요?

맞아요! 자주쓰는 Service/Helper Class에서 비슷한 구조를 사용하고 있잖아요!

class ProductService{
	ProductHelper helper = new ProductHelper();
	public void getProductDataList(){
		helper.getProductData();	//helper에게 위임한다.
	}
}

class ProductHelper{
	void getProductData(){
		
	}
}

수정영역이 지역화되는것을 알 수 있다.

우리는 무의식적으로 개발을 하면서 패턴을 사용하고 있었구나.

댓글