: ์์กด์ฑ ์ฃผ์
๊ฐ์ฒด๋ฅผ ์ง์ ์์ฑํ๋ ๊ฒ์ด ์๋๋ผ ์ธ๋ถ์์ ์์ฑํ ํ ์ฃผ์
์ ์์ผ์ฃผ๋ ๋ฐฉ์์ด๋ค.
public class Consumer {
Food food;
void eat() {
this.food.eat();
}
public static void main(String[] args) {
Consumer consumer = new Consumer();
consumer.food = new Chicken();
consumer.eat();
consumer.food = new Pizza();
consumer.eat();
}
}
interface Food {
void eat();
}
class Chicken implements Food{
@Override
public void eat() {
System.out.println("์นํจ์ ๋จน๋๋ค.");
}
}
class Pizza implements Food{
@Override
public void eat() {
System.out.println("ํผ์๋ฅผ ๋จน๋๋ค.");
}
}
public class Consumer {
Food food;
void eat() {
this.food.eat();
}
public void setFood(Food food) {
this.food = food;
}
public static void main(String[] args) {
Consumer consumer = new Consumer();
consumer.setFood(new Chicken());
consumer.eat();
consumer.setFood(new Pizza());
consumer.eat();
}
}
interface Food {
void eat();
}
class Chicken implements Food{
@Override
public void eat() {
System.out.println("์นํจ์ ๋จน๋๋ค.");
}
}
class Pizza implements Food{
@Override
public void eat() {
System.out.println("ํผ์๋ฅผ ๋จน๋๋ค.");
}
}
public class Consumer {
Food food;
public Consumer(Food food) {
this.food = food;
}
void eat() {
this.food.eat();
}
public static void main(String[] args) {
Consumer consumer = new Consumer(new Chicken());
consumer.eat();
consumer = new Consumer(new Pizza());
consumer.eat();
}
}
interface Food {
void eat();
}
class Chicken implements Food{
@Override
public void eat() {
System.out.println("์นํจ์ ๋จน๋๋ค.");
}
}
class Pizza implements Food{
@Override
public void eat() {
System.out.println("ํผ์๋ฅผ ๋จน๋๋ค.");
}
}
: ์ ์ด์ ์ญ์
Consumer๊ฐ ์ง์ food๋ฅผ ๋ง๋ค์๊ธฐ ๋๋ฌธ์ ์๋ก์ด Food๋ฅผ ๋ง๋ค๊ธฐ ์ํด์ ์ถ๊ฐ์ ์ธ ์ฝ๋๋ณ๊ฒฝ์ด ํ์ํ๋ค.
์ ์ดํ๋ฆ: Consumer โ food
food โ Consumer ๋ก ์ ์ดํ๋ฆ์ ๋ฐ๊พธ์ด ๋ง์ ์ฝ๋๋ณ๊ฒฝ์ด ํ์ํ์ง ์๋ค.
[IoC]
1. ๊ฐ์ฒด ์์ฑ
2. ์์กด์ฑ ๊ฐ์ฒด ์ฃผ์
- ์ค์ค๋ก๊ฐ ๋ง๋๋ ๊ฒ์ด ์๋๋ผ ์ ์ด๊ถ์ Spring์์ ์์ํ์ฌ Spring์ด ๋ง๋ค์ด๋์ ๊ฐ์ฒด๋ฅผ ์ฃผ์
ํ๋ค.
3. ์์กด์ฑ ๊ฐ์ฒด ๋ฉ์๋ ํธ์ถ