Java Class Notes

Ex - Customer Account

헤일리유 2023. 3. 10. 13:56

 

 

Customer


DB를 사용하지 않고 클래스 파일이 실행되는 동안에만 사용자의 id, pw, email, name, date created 를 저장할 수 있는 프로그램.

사용자가 저장한 정보를 수정할 수 있다. (등록하려는 id가 중복이거나 암호가 다르거나 하면 등록/수정 할 수 없다. )

 

 

 

 

                         customer                              customer : DTO(Data Transfer Object), VO(Value Object)

 Ex01(콘솔,웹)      -------------->      CustomerServiceImpl      ----------->   CustomerDaoImpl

                                                                    Business Model                                    

1)     입력               ------입력요청----->           업무처리          ----------->     Map을 통해 메모리에 데이터 처리

                                                                 (있는 데이터인지 확인)

     다시 입력           <------ 있다면 ------        select(id)                                                 (CRUD)

                                                                         select(id)      ---- 없다면 --->      DB에 입력/조회/수정/ 삭제

     입력 성공           <-------------------        select(id)    -- insert(customer)-->  map.put (id.customer)

 

2)         조회         <------select(id)------>                      <------select(id)------>     map.get(id)

toString()메서드로 읽은 값 출력

 

 

 

 

 

Customer 

- customer 객체의 베이스

- 생성자로 초기화 가능 (id, pw, email, name, reg_date)

- private ivs 

- getters and setters

package customer;

import java.util.Date;

public class Customer {	// DTO (Data Transfer Object), VO (Value Object)
	private String id;	private String pass;	private String email;
	private String name;	private Date reg_date;
	public Customer() {}
	public Customer(String id, String pass, String email, String name, Date reg_date) {
		this.id=id; this.pass=pass; this.email=email; this.name=name; this.reg_date=reg_date;
	}
	public String toString() {
		return "id:"+id+", pw:"+pass+", email:"+email+", name:"+name+", reg_date: "+reg_date;
	}
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getReg_date() {
		return reg_date;
	}
	public void setReg_date(Date reg_date) {
		this.reg_date = reg_date;
	}
	
	
}

 

 

 

CustomerDaoImpl

- data store (create / read / update(re-write) / delete)

- HashMap / Map (map의 메소드는 자바 api 에서 java.map에 가면 찾아볼 수 있다)

package customer;
// DTO 형식으로 전달받은 데이터를 DB에 저장 
// But 오늘은 map에 저장, temporary, 프로그램 종료하면 사라짐
// 저장 / 조회 / 수정 / 삭제 
// create / read / update / delete : CRUD

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class CustomerDaoImpl {	// DAO : Data Access Object
	
	private Map<String, Customer> map = new HashMap<>();
	
	public Customer select(String id) { // k1,1,k1@k.com,Kim,today
		return map.get(id);		// id에 해당하는 값 customer 
	}
	
	public int insert(Customer customer) {
		map.put(customer.getId(), customer);
		return 1;
	}

	public int update(Customer customer) {
		map.put(customer.getId(), customer); // 현재 값을 덮어쓰기 // map은 수정이 따로 없다 
		return 1;
	}
	public int delete (String id) {
		map.remove(id);  
		return 1;
	}

	public Collection<Customer> list() {	
		return map.values();	// map에서 모든 값만 추출 
	}

}

 

 

 

CustomerService

- pass auguments(parameters)

- 중간 역할 중복 데이터 같은 것들을 체크해줌 

- 실행 성공 / 실패 체크 

package customer;

import java.util.Collection;

public class CustomerServiceImpl {	// Business Model 업무처리 
	
	private static CustomerDaoImpl cdi = new CustomerDaoImpl();

	public int insert(Customer customer) {  // id, p/w, email, name, date 
		int	result = 0;	// 0은 입력 실패, 1은 입력 성공 
		// map에 전달된 id를 가지고 읽어서 있으면 이미 있는 id입니다. 다른 아이디를 입력해주세요.
		// 없으면 전달 받은 데이터를 insert  
		// customer : console로 입력 받아서 전달 받은 데이터, customer2 : map에서 읽어온 데이터 
		Customer customer2 = cdi.select(customer.getId()); // 입력한 id로 읽기 
		if (customer2 == null) {result=cdi.insert(customer);}
		else System.out.println("이미 사용중인 id입니다. 다른 아이디를 입력해주세요.");
		return result;
	}

	public Customer select(String id) {
		return cdi.select(id);
	}

	public int update(Customer customer) {
		int	result = 0;	// 0은 입력 실패, 1은 입력 성공 
		Customer customer2 = cdi.select(customer.getId()); // 입력한 id로 읽기 
		if (customer2 != null) {result=cdi.update(customer);}
		else System.out.println("수정할 데이터가 없습니다.");
		return result;
	}

	public int delete(String id) {
		return cdi.delete(id);
	}

	public Collection<Customer> list() {
		return cdi.list();
	}
	
	
}

 

 

 

 

Ex01

- Get inputs and check if it's in appropriate form. If it is, then pass it to other classes' methods

 

package customer;

import java.util.*;

public class Ex01 {

	private static CustomerServiceImpl csi = new CustomerServiceImpl();

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		String command = "";
		while (true) {
			help();
			System.out.println("명령어를 입력하세요 ");
			command = sc.nextLine();
			if (command.equals("x")) break;	// program end 
			else if (command.startsWith("insert")) {	// insert로 시작한 명령어 
				// 컴마로 나눠 배열로 만들어 insert라는 메서드에 매개변수로 전달 
				insert(command.split(","));	 
			}  else if (command.startsWith("update")) update(command.split(","));
			else if (command.startsWith("select")) select(command.split(","));
			else if (command.startsWith("delete")) delete(command.split(","));
			else if (command.equals("list")) list();
			else help();
		}
		sc.close();
		System.out.println("프로그램 종료");
		
	}
	
	
	private static void list() {
		Collection<Customer> list = csi.list();
		if (list==null || list.size()==0) {
			System.out.println("No user data found");
		} else {
			for(Customer customer:list) {
				System.out.println(customer);
			}
		}
	}


	private static void delete(String[] str) {
		if (str.length != 2) {
			help();	return;	// 메서드 종료 
		} 
		Customer customer = csi.select(str[1]);
		if (customer == null) System.out.println("없는 고객입니다 ");
		else { 
			int result = csi.delete(str[1]);
			if (result>0) System.out.println("삭제 완료 ");
		}
	}


	private static void update(String[] str) {
		if (str.length != 6) {
			help();	return;	// 메서드 종료 
		} 
		Customer customer = new Customer(str[1], str[2], str[4], str[5], new Date());
		if (!str[2].equals(str[3])) {
			System.out.println("Your password doesn't match your password confirmation");
			return;
		}
		int result = csi.update(customer);
		if (result>0) System.out.println("수정 완료  ");
	}
	
	
	private static void select(String[] str) {
		if (str.length != 2) {
			help();	return;	// 메서드 종료 
		} 
		Customer customer = csi.select(str[1]);
		if (customer == null) System.out.println("없는 고객입니다 ");
		else System.out.println(customer);
		
	}

	private static void insert(String[] str) {
		if (str.length != 6) {
			help();	return;	// 메서드 종료 
		} 
		Customer customer = new Customer(str[1], str[2], str[4], str[5], new Date());
		if (!str[2].equals(str[3])) {
			System.out.println("Passwords don't match, please check your password.");
			return;
		}
		int result = csi.insert(customer);
		if (result>0) System.out.println("고객 등록 성공 ");
	}

	private static void help() {
		System.out.println("다음 명령어 중에서 사용하시오 ");
		System.out.println("insert, id, password, pw confirm, email, name ");
		System.out.println("update, id, password, pw confirm, email, name ");
		System.out.println("delete, id");
		System.out.println("select, id");
		System.out.println("list");
		System.out.println("x");
	}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

'Java Class Notes' 카테고리의 다른 글

Network (네트워크)  (0) 2023.03.15
Thread(스레드)  (0) 2023.03.10
Genetic and Collection (제네릭과 컬렉션)  (0) 2023.03.06
Exception (예외처리)  (0) 2023.03.03
javaLang (주요 클래스)  (0) 2023.02.28