์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

๋นŒ๋”ํŒจํ„ด ์ง์ ‘ ๊ตฌํ˜„ํ•ด๋ณด๊ธฐ

CS/๋””์ž์ธํŒจํ„ด OOP

by :ํ•ดํ”ผ๋ž˜๋น—๐Ÿพ 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

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ