팩토리 패턴

jinkyung·2021년 2월 9일
0

Spring

목록 보기
2/24

결합도를 낮추는 방법에 팩토리 패턴이 있다.

BeanFactory

package polymorphism;

public class BeanFactory {
	public Object getBean(String beanName) {
		if(beanName.equals("samsung"))
			return new SamsungTV();
		else if(beanName.equals("lg"))
			return new LgTV();
		else if(beanName.equals("sony"))
			return new SonyTV();
		
		return null;
	}
}

TVUser

package polymorphism;

public class TVUser {
	public static void main(String[] args) {
	/*
	결합도를 낮추기 위해 Factory Pattern을 사용 
	*/
		BeanFactory factory = new BeanFactory();
		TV tv = (TV)factory.getBean("sony");
		tv.powerOn();
		tv.powerOff();
		tv.volumeUp();
		tv.volumeDown();
		
	}
}

BeanFactory

package polymorphism;

import java.util.HashMap;
import java.util.Map;

public class BeanFactory {
	Map<String, Object> map = new HashMap<String,Object>();
	
	public void regBean(String bean, String className) {
		try {
			map.put(bean, Class.forName(className).newInstance());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public Object getBean(String beanName) {
		return map.get(beanName);
	}
}

TVUser

package polymorphism;

public class TVUser {
	static BeanFactory factory = new BeanFactory();
	
	
	public static void main(String[] args) {
		factory.regBean("samsung", "polymorphism.SamsungTV");
		factory.regBean("lg", "polymorphism.LgTV");
		factory.regBean("sony", "polymorphism.SonyTV");
		
		
		TV tv = (TV)factory.getBean("sony");
		tv.powerOn();
		tv.powerOff();
		tv.volumeUp();
		tv.volumeDown();
		
	}
}

0개의 댓글