티스토리 뷰

직전 포스팅에서는 생성자에 인자를 부여하여 그 인자를 constructor-arg 태그로 전달했다면, 이번에는 생성자가 아닌 setter를 구성하여 property 태그를 이용하여 값을 설정해줄 것이다. 

 

구조는 거의 비슷하다.


◎SamsungTV

package polymorphism;

public class SamsungTV implements TV{
	
	private Speaker speaker = null;
	private int price = 0;
	
	public SamsungTV() {
		System.out.println("SamsungTV --- 객체 생성");
	}

	public void setSpeaker(Speaker speaker) {
		System.out.println("setSpeaker");
		this.speaker = speaker;
	}

	public void setPrice(int price) {
		System.out.println("setPrice");
		this.price = price;
	}

	@Override
	public void powerOn() {
		System.out.println("SamsungTV --- 전원 켜기");
	}

	@Override
	public void powerOff() {
		System.out.println("SamsungTV --- 전원 끄기");
	}

	@Override
	public void volumeUp() {
		//System.out.println("SamsungTV --- 볼륨 켜기");
		speaker.volumeUp();
		System.out.println(this.price);
	}

	@Override
	public void volumeDown() {
		//System.out.println("SamsungTV --- 볼륨 줄이기");
		speaker.volumeDown();
	}
	
}

◎applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id = "tv" class = "polymorphism.SamsungTV">
		<property name = "speaker" ref = "sony"></property>
		<property name = "price" value = "270000"></property>
	</bean>
	
	<bean id = "sony" class = "polymorphism.SonySpeaker"></bean>

</beans>

반응형
Comments