JAVA

자바_커피 머신 구현

물고기는피쉬 2022. 2. 22. 14:28

오늘은 자바로 아주 간단하게 커피 머신을 만들어 보도록 하겠습니다.

 

내용은 대충 이렇습니다. 커피 머신에 4종류의 커피가 들어 있고, 먹고 싶은 종류를 클릭하면 해당 커피가 출력되는 형태입니다. 이때 배열의 각 인덱스에 있는 커피 위치는 동적으로 할당할 수 있습니다. 다시 말해, 인덱스 0에 아메리카노를 지정해 놓아도 본인이 그 위치에 다른 것을 할당하고 싶으면 바꿀 수 있습니다.

 

public class CoffeeMC {
	private Button btns[] = new Button[4];
	
	// 버튼 추가 기능
	public void addButton(int _idx, Button _btn) {
		if (_idx < 0 || _idx > btns.length)
			return;
		btns[_idx] = _btn;
	}
	
	// 전체 출력 기능
	public void printAll() {
		for (int i = 0; i < btns.length; ++i)
		{
			if (btns[i] != null) 
			System.out.println((i + 1) + ": " + btns[i].GetCategory()); 
		}
	}
	
	// 버튼 클릭 기능
	public void onClickButton(int _idx) {
		if (btns[_idx] != null)
			btns[_idx].onClick();
	}
}

 

public abstract class Button {
	private String category = "";
	
	public String GetCategory() {
		return category;
	}
	
	public abstract void onClick();
	
	public Button(String _category) {
		this.category = _category;
	}
}

 

// 아메리카노
public class ButtonAmericano extends Button {
	public ButtonAmericano() {
		super("Americano");
	}
	
	public void onClick() {
		System.out.println(this.GetCategory() + " Click");
	}
}

// 에스프레소
public class ButtonEspresso extends Button {
	public ButtonEspresso() {
		super("Espresso");
	}
	
	public void onClick() {
		System.out.println(this.GetCategory() + " Click");
	}	
}

// 헤이즐럿
public class ButtonHazelunt extends Button {
	public ButtonHazelunt() {
		super("Hazelunt");
	}
	
	public void onClick() {
		System.out.println(this.GetCategory() + " Click");
	}
}

// 라떼
public class ButtonLatte extends Button {
	public ButtonLatte() {
		super("Latte");
	}
	
	public void onClick() {
		System.out.println(this.GetCategory() + " Click");
	}
}

 

마지막으로 커피 머신을 구현시키기 위해 커피 머신 클래스에 해당하는 객체를 작성하였습니다.

 

public class Action {

	public static void main(String[] args) {
		CoffeeMC cof = new CoffeeMC();
		cof.addButton(0, new ButtonHazelunt());
		cof.addButton(1, new ButtonAmericano());
		cof.addButton(2, new ButtonEspresso());
		cof.addButton(3, new ButtonLatte());
		cof.printAll();
		cof.onClickButton(2);
	}
}

 

결과는 다음과 같습니다.

 

1: Hazelunt
2: Americano
3: Espresso
4: Latte
Espresso Click

 

동적 할당이 가능하게끔 만들었으므로 다음과 같이 바꾸어 결과를 출력할 수 있습니다.

 

public class Action {

	public static void main(String[] args) {
		CoffeeMC cof = new CoffeeMC();
		cof.addButton(0, new ButtonAmericano());
		cof.addButton(1, new ButtonEspresso());
		cof.addButton(2, new ButtonHazelunt());
		cof.addButton(3, new ButtonLatte());
		cof.printAll();
		cof.onClickButton(2);
	}
}

 

출력값

 

1: Americano
2: Espresso
3: Hazelunt
4: Latte
Hazelunt Click

 

이것으로 해당 블로그 작성을 마치도록 하겠습니다. 감사합니다.