코딩 기록들

[Java Programming] 6.2 클래스 다이어그램 & Vending Machine 예제 본문

Java

[Java Programming] 6.2 클래스 다이어그램 & Vending Machine 예제

코딩펭귄 2024. 1. 24. 17:30

다이어그램 그리는 순서

1. 클래스 다이어그램 -> 2. 시퀀스다이어그램 -> 3. 플로우 다이어그램

 

Vending Machine 예제코드

[ 클래스 다이어그램 ]

Customer

- wallet : int
- product : Product
+ getWallet() : int
+ getProduct() : Product
+ (int)
+ pay(int) : void
+ addStock(String, int) : void

 

VendingMachine

- product : Product
- money : int
+ getProduct()
+ getMoney()
+ (Product)
+ pressButton(Customer) : void

 

Mart

+ main : void

 

Product

- name : String
- price : int
- quantity : int
+ getName() : String
+ getPrice() : int
+ getQuantity() : int
+ setName(String) : void
+ setPrice(int) : void
+ setQuantity(int) : void

 

 

package vending_machine;

public class VendingMachine {

	// 클래스상수 (공용상수)
	/**
	 * 한번에 구매할수있는 제품의 수
	 */
	public static final int PRODUCT_COUNT; // 한번에 구매할 수 있는 제품의 수 = 1개 라고 정의해 놓은것
	public static final String MACHINE_NAME;
	
	//클래스 상수에 값을 할당하는 방법
	// -> static block
	static {
		// static변수, 상수의 값을 초기화 하는 공간
		PRODUCT_COUNT = 2;
		MACHINE_NAME = "자판기";
	}
	
	// -> 이거를 다른곳에서 사용할때 : VendingMachine.MACHINE_NAME
	
	//상수 자리 (클래스 바로밑, 대문자로 작성)

		
	// 멤버변수 자리
	/**
	 * 상품 수량
	 */
	private Product product;
	
	/**
	 * 돈
	 */
	private int money;

	
	//Getter만들기
	public Product getProduct() {
		return this.product;
	}
	public int getMoney() {
		return this.money;
	}
	
	
	// 생성자 자리 (생성자는 반환타입이 들어가지 않음)
		/**
		 * VendingMachine의 인스턴스를 생성할때 호출됨
		*/
	public VendingMachine() {
		System.out.println("자판기 인스턴스를 만들었습니다!");
		this.product = new Product();
		this.product.setName("제로콜라");
		this.product.setPrice(1600);
		this.product.setQuantity(50);

		this.money = 100_000;
		/*
		 * 생성자를 직접 만드는 이유
		 * 1. 멤버변수를 초기화 하기 위해(멤버변수에 기본값을 별도로 할당을 하기 위해)
		 *   - 특히, Reference Type 위주로 초기화
		 * 	    - ex) 배열, 컬렉션 
		 * 2. 인스턴스 생성과 동시에 다른 메소드를 호출하기 위해서 사용
		 *   - ex) 인스턴스를 생성함과 동시에 insertMoney메소드를 호출하기 위해
		 */
	}
		
	//기능
	/**
	 * 돈을 넣는다
	 * @param customer 돈을 넣은고객
	 */
	
	public void insertMoney(Customer customer) {
		this.money += this.product.getPrice(); // 자판기 돈 증가시킴 //여기서 this = drinkMachine 
		customer.pay(this.product.getPrice()); // 고객의 지갑에서 PRICE만큼 감소
		// 내 인스턴스의 product에서 getPrice()값을 가져와라
	}
		
		/**
		 * 버튼을 누른다
		 * @param customer 버튼을 누른 고객
		 */
	public void pressButton(Customer customer) {
		// 자판기에 상품이 없는상태

		if(this.product.getQuantity() <= 0) {
			return; //메소드 즉시종료
		}
		int quantity = this.product.getQuantity();
		quantity--;
		
		quantity -= VendingMachine.PRODUCT_COUNT;
		this.product.setQuantity(quantity);
		customer.addStock(this.product.getName(), this.product.getPrice());			
	}
}

 

package vending_machine;

/**
 * 자판기에서 판매할 상품의 정보 (데이터클래스)
 */
public class Product {

	/**
	 * 상품의 이름
	 */
	private String name; // 정보안주면 null 할당됨
	
	/**
	 * 상품의 가격
	 */
	private int price; // 정보안주면 0 할당됨
	
	/**
	 * 상품의 재고 (수량 관리 위함)
	 */
	private int quantity; 
	
	
	// Getter 만들기
	public String getName() {
		return this.name;
	}
	public int getPrice() {
		return this.price;
	}
	public int getQuantity() {
		return this.quantity;
	}
	
	//setter // 파라미터 : 멤버변수의 타입과 이름 똑같이 작성
	public void setName(String name) { 
		this.name = name;
	}
	public void setPrice(int price) { 
		this.price = price;
	}
	public void setQuantity(int quantity) { 
		this.quantity = quantity;
	}

}

 

package vending_machine;

public class Mart {
	/**
	 * 함수지향방식으로 개발한 코드
	 */
	public static void case1() {
		
		VendingMachine drinkMachine = new VendingMachine();
		
		Customer musk = new Customer(0);
		
		//고객이 자판기에 돈을 넣는다.
		// 고객이 가진돈을 뺴주고
		musk.pay(1300);
		// 자판기의 돈을 증가시킨다
		//drinkMachine.insertMoney();
		
		//고객이 자판기의 음료버튼을 누른다
		// 자판기 수량이 하나 줄어들고,
		//drinkMachine.pressButton();
		
		//고객수량이 하나 증가한다.
		musk.addStock("", 0);
		
		System.out.println("자판기의 잔액: " + drinkMachine.getMoney());
		System.out.println("자판기의 상품 수량: " + drinkMachine.getProduct().getQuantity());
		System.out.println("고객의 지갑 잔액: " + musk.getWallet());
		System.out.println("자판기에 남은 상품 수량: " + musk.getProduct().getQuantity());
	
	}

	public static void main(String[] args) {
	
		// 캡슐화 : 기능 1개에서 여러 처리를 하는 특징
		
		// 객체지향 방식으로 개발
		VendingMachine drinkMachine = new VendingMachine();

		Customer musk = new Customer(200_000);

		// 파라미터 영역에 누가 행동을 할건지 적어줌
		drinkMachine.insertMoney(musk);
		drinkMachine.pressButton(musk);

		System.out.println("자판기의 잔액: " + drinkMachine.getMoney());
		System.out.println("자판기의 상품 수량: " + drinkMachine.getProduct().getQuantity());
		System.out.println("자판기의 상품 이름: " + drinkMachine.getProduct().getName());
		System.out.println("고객의 지갑 잔액: " + musk.getWallet());
		System.out.println("자판기에 남은 상품 수량: " + musk.getProduct().getQuantity());
	}
}
package vending_machine;

public class Customer {
	/**
	 * 고객이 가진 돈 (멤버변수 = 파란색으로 보임)
	 */
	private int wallet;
		
	/**
	 * 고객이가진 상품수량
	 */
	//int stock;
	// 자판기와 연동을 위해 같은 타입으로 작성해줌
	private Product product;	
	
	/**
	 * 생성자
	 */
	//public Customer(int wallet, int stock) { // 갈색변수인 wallet, stock = 파라미터 
	public Customer(int wallet) { 
		// musk를 뜻하는 this를 붙여줘야됨
		// 생성자에서 this의 의미 : 생성자가 만들어준 인스턴스
		this.wallet = wallet; // 생성자가 만들어준 wallet에 파라미터로 받은 wallet을 넣어라
		//this.stock = stock;
		this.product = new Product(); // 이상태에서는 일종의 장바구니라고 생각하기(아무것도 없는 상태(아래 추가코드 안쓰면))
	}
		
	//Getter만들기
		public int getWallet() {
			return this.wallet;
		}
		public Product getProduct() {
			return this.product;
		}
	
	/**
	 * 지출한다 - price를 파라미터로 받아옴
	 */
	public void pay(int price) {
		if ( this.wallet - price <= 0) {
				return; //메소드 즉시종료
		}
		this.wallet -= price;
	}	
	/**
	 * 상품이 하나 증가한다
	 */
	public void addStock(String name, int price) {
		//this.stock++;
		// 고객이 제로콜라를 구매한 적이 있는지 확인 (구매한적 없다면 데이터 및 수량만 증가시킴)	
		// 고객이 제로콜라 구매한적이 없다면
		
		// 값을 가져올때는 Getter
		if(this.product.getName() == null) {
			// 고객이가진 상품의정보를 제로콜라로 채워줌
			// 값을 할당할때는 Setter
			this.product.setName(name);
			this.product.setPrice(price);
//			this.product.setQuantity(1);
			this.product.setQuantity(VendingMachine.PRODUCT_COUNT);
		}
		// 고객이 제로콜라 구매한적이 있다면(= null이 아니라면) -> (구매한적 있다면 수량만 증가시킴)
		else {
			// 고객이가진 제로콜라의 수량을 1개 증가 시킴
			//this.product.quantity++; -> 아래3줄로 풀어서 씀
			int quantity = this.product.getQuantity();
//			quantity++;
			quantity += VendingMachine.PRODUCT_COUNT;
			this.product.setQuantity(quantity);
		}
	}
}

 

 

예제2. 만화카페 구현해보기

1st : 멤버변수 뭐가 필요할지 생각해보기

1. 만화책 book -> 기능이 없으므로, 데이터클래스가 됨

-- 만화책에서 관리해야하는 변수 : 만화책 이름 bookName / 대여상태 / 대여비

2.  만화카페

3. 고객이라는 클래스는 없어도 문제될게 없다!