상세 컨텐츠

본문 제목

빌더패턴 직접 구현해보기

CS구멍/디자인패턴

by :Eundms 2024. 11. 5. 20:31

본문

public class Item {
	private int id;
	private String name;
	private int price;
	private int count;

	private Item(int id, String name, int price, int count) {
		this.id = id;
		this.name = name;
		this.price = price;
		this.count = count;
	}

	@Override
	public String toString() {
		return "" + this.id + " " + this.name + " " + this.price + " " + this.count;
	}

	public static ItemBuilder builder() {
		return new ItemBuilder();
	}

	public static class ItemBuilder {
		private int id;
		private String name;
		private int price;
		private int count;

		public ItemBuilder id(int id) {
			this.id = id;
			return this;
		}

		public ItemBuilder name(String name) {
			this.name = name;
			return this;
		}

		public ItemBuilder price(int price) {
			this.price = price;
			return this;
		}

		public ItemBuilder count(int count) {
			this.count = count;
			return this;
		}

		public Item build() {
			return new Item(id, name, price, count);
		}
	}

}

 

테스트 

더보기

 

public class Main {

	public static void main(String[] args) throws Exception {
		Item item = Item.builder().id(1).name("수건").price(1400).count(5).build();
		System.out.println(item);

		Item item2 = Item.builder().id(1).name("수건").price(1400).count(5).build();
		System.out.println(item2);

		System.out.println(item == item2);
	}
}
728x90

관련글 더보기

댓글 영역