[실습으로 다지는 C#] 집합(Aggregation) 관계 실습 – 쇼핑 센터, 상품

 이번 강의는 집합(Aggregation) 관계를 코드로 표현하는 실습입니다.

 실습 소재는 쇼핑 센터와 상품입니다. 집합 관계는 이처럼 컬렉션과 원소 사이의 관계입니다. 

 상품은 상품 이름, 가격, 회사 이름, 일련 번호를 갖습니다. 일련 번호는 순차적으로 자동 부여하며 상품은 쇼핑 센터에 입고할 수 있게 표현해 봅시다.

 먼저 클래스 다이어그램을 작성해 보세요. 

집합 관계 클래스 다이어그램

 이를 코드로 작성합시다. 

namespace 집합_관계
{
    public class Product
    {
        public string Name
        {
            get;
            private set;
        }
        public int Price
        {
            get;
            private set;
        }
        public string Company
        {
            get;
            private set;
        }
        readonly int pn;
        public int PN
        {
            get
            {
                return pn;
            }
        }
        static int lastpn;
        public Product(string name,int price,string company)
        {
            Name = name;
            Price = price;
            Company = company;
            lastpn++;
            pn = lastpn;
        }
        public override string ToString()
        {
            return Name;
        }
    }
}
using System.Collections;
using System.Collections.Generic;

namespace 집합_관계
{
    class Mall : IEnumerable
    {
        Dictionary<int, Product> pdic = new Dictionary<int, Product>();

        public bool InProduct(Product product)
        {
            if(pdic.ContainsKey(product.PN))
            {
                return false;
            }
            pdic[product.PN] = product;
            return true;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return pdic.Values.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return pdic.GetEnumerator();
        }
    }
}

//https://ehpub.co.kr
//실습으로 다지는 C#
//집합 관계 실습
using System;

namespace 집합_관계
{
    class Program
    {
        static void Main(string[] args)
        {
            Mall mall = new Mall();
            mall.InProduct(new Product("Escort C#", 5000, "언제나 휴일"));
            mall.InProduct(new Product("실습으로 다지는 C#", 5000, "휴일"));
            foreach(Product product in mall)
            {
                Console.WriteLine(product);
            }
        }
    }
}