본문 바로가기
JAVA

UI코드 분리 하기

by 영카이브 2024. 1. 10.

UI 코드란?

  • User Interface의 약자로, 사용자와 시스템 간의 상호 작용을 담당하는 부분
  • 사용자가 컴퓨터 프로그램 또는 모바일 앱을 사용할 때 마주하는 디자인, 레이아웃 등 직접 눈으로 보이는 것
  • 디자인적 요소와 사용자의 입력에 의해서 발생하는 동작 등의 모든 것을 말하며 예를 들어, 사용자가 어떤 버튼을 누르거나 화면 상의 어떤 요소에 상호 작용하는 것은 UI 코드에 해당한다.
  • 간단히 말하면, UI 코드는 사용자와 시스템 간의 의사 소통을 도와주는 부분으로, 사용자가 프로그램을 어떻게 사용하는지에 대한 경험을 디자인하고 구현하고 디자인적인 측면뿐만 아니라 사용자의 입력을 받아들이고 처리하는 로직 등도 포함하고 있다.

UI를 이루는 세 가지 수단

  • 입력 : 사용자가 시스템을 조작할 수 있도록 한다.(키보드 입력, 마우스 클릭, 스마트폰 터치 등)
  • 출력 : 시스템이 사용자의 입력으로 부터의 결과물을 표시한다.(모니터, 스피커, 스마트폰 화면 등의 표시)
  • 삭제 : 시스템이 사용자가 잘못 입력한 것들을 삭제한다.

 

UI코드를 분리하는 이유

  • 캡슐을 분리하는 작업은 앞으로 변화가 이뤄질 부분에 대해서는 분리하는 것이 좋다. 
  • 입 / 출력은 일반적으로 콘솔, 윈도우, 웹, 모바일 플랫폼에서 이뤄지며 어떤 UI 플랫폼을 쓰느냐에 따라 달라진다. 나머지 코드는 UI가 달라져도 재사용이 가능하다. 일체화된 데이터관리 클래스에서는 콘솔외에 재사용이 어려우므로 편리하도록 분리하는 것이 좋다.

UI코드 분리 결과

  • 기존 Program - Product - Inventory 구조에서 Program - Product - Inventory - InventoryConsole로 바꿈
  • Inventory클래스에 있던 입출력부분은 따로 InventoryConsole에서 input() 과 output() 으로 분리
  • 재고에 상품을 추가하는 add(), 재고에서 상품을 꺼내오는 get() 은 Inventory클래스에 로직과 함께 추가
  • InventoryConsole클래스에선 현재 쓰이는 멤버변수가 아니므로 this를 쓰지 못함 따라서 Inventory객체생성후 inventory.으로 메서드 사용
public class Program {
	public static void main(String[] args) {
		InventoryConsole inventory = new InventoryConsole(); 

		int menu; 
		boolean keepLoop=true;
		
		while(keepLoop) {
			menu=inputMenu();
			switch(menu) 
			{
			case 1:
				inventory.inputInventory();
				break; 
			case 2 :
				inventory.outputInventory();
				break;
			case 3 : 
				System.out.println("종료");
				keepLoop=false;
				break;
			default :
				System.out.println("메뉴는 1~3번까지 입니다.");
			}	
		}
	}

	private static int inputMenu() {
		Scanner sc = new Scanner(System.in);
		System.out.println("1.상품 입력 ");
		System.out.println("2.재고 출력 ");
		System.out.println("3.종료");
		int menu=sc.nextInt();
		return menu;
	}
}
public class Product {
	String name;
	int price; 
	int quantity;
	
	public Product() {
		this("Undefined", 0, 0);
	}
	
	public Product(String name, int price, int quantity) {
		this.name = name;
		this.price = price;
		this.quantity = quantity;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	
}
public class Inventory {
	private Product[] products;
	private int current; 
	
	public Inventory() {
		this(5);
	}	
	
	public Inventory(int size) {
		this.products = new Product[size]; 
		this.current=0; 
	}

	public Product[] getProducts() {
		return products;
	}

	public void setProducts(Product[] products) {
		this.products = products;
	}

	public int getCurrent() {
		return current;
	}

	public void setCurrent(int current) {
		this.current = current;
	}

	public int size() {
		return this.current;
	}

	// 상품을 재고목록에 추가 
	public void add(Product product) {
		Product[] products = this.products;
		int size = this.size(); 
		if(products.length==size) {
			Product[] temp = new Product[size+3]; 
			for( int i=0; i<size; i++) {
				temp[i]=products[i]; 
			}
			products = temp;
			this.products=products;
		}
		products[size]=product;
		current++;
	}

	public Product get(int i) {
		return products[i];
	}
}
public class InventoryConsole {
	Inventory inventory = new Inventory();
	
	public void inputInventory() {
		Scanner sc = new Scanner(System.in);
		System.out.println("상품 입력");
		
		String name; 
		int price, quantity;
		
		System.out.printf("상품 이름 : "); 
		name=sc.next();
		do {
			System.out.print("가격 : ");
			price=sc.nextInt();
			if(price<0) {
				System.out.println("가격은 0보다 커야합니다.");
			}
		}while(price<0);
		do {
			System.out.print("수량 : ");
			quantity=sc.nextInt();
			if(quantity<0) {
				System.out.println("수량은 0보다 커야합니다.");
			}
		}while(quantity<0);
		
		Product product= new Product(name, price, quantity); 
		// 더하는 메서드 
		inventory.add(product);
		
	}
	
	// 재고목록 총 출력 
	public void outputInventory() {
		this.outputInventory(inventory.size());
	}

	// 재고목록 필요범위까지만 출력
	public void outputInventory(int size) {
		System.out.println("상품 출력");
		
		for( int i=0; i<size; i++) {
			// 재고목록에서 상품을 꺼내는 메서드 get()
			Product product = inventory.get(i);
			String name = product.getName(); 
			int price = product.getPrice();
			int quantity = product.getQuantity();
			System.out.println( "상품 이름 : " + name);
			System.out.println( "상품 가격 : " + price);
			System.out.println( "상품 수량 : " + quantity);
		}		
	}
}

 

이전 코드와 비교 : https://young-s-note.tistory.com/45

 

 

참고 자료 출처 : https://www.youtube.com/watch?v=efMRwQwxmJM&list=PLq8wAnVUcTFX4E2NplMvJfqlcgAeF_BxK&index=10

'JAVA' 카테고리의 다른 글

코드 재사용  (0) 2024.01.14
Has A 관계  (0) 2024.01.11
Setter 대신 Overload 생성자 이용하기  (0) 2024.01.09
Getter 와 Setter  (0) 2024.01.07
데이터 구조화  (0) 2024.01.07