24.클래스의 양방향 연결을 단방향으로 전환 Change Bidirectional Association to Unidirectional

서로 링크를 가지는 두 개의 클래스에서 한 쪽이 다른 한쪽을 필요로 하지 않을 때는 불필요한 링크를 제거한다.

양방향 바인딩은 비용 발생과 복잡성이 증가하는 단점이 존재한다.→ 두 클래스간의 종속성이 존재할 수 밖에 없으므로 시스템의 결합성이 높아진다.

클래스의 양방향 연결을 단방향으로 전환
/**
*두 클래스가 양방향으로 연결되어 있는데 한 클래스가 다른 클래스의 기능을 더 이상 사용하지 않게 됐을 땐 불필요한 방*향의 연결을 쓰자.
*/
 
 /* 양방향 연결 */
class Order
    {
        private Customer customer;

        public Customer getCustomer()
        {
            return customer;
        }

        public void SetCustomer(Customer customer)
        {
            if (this.customer != null) this.customer.FriendOrders().Remove(this);
            this.customer = customer;
            if (this.customer != null) this.customer.FriendOrders().Add(this);
        }
    }

class Customer
    {
        private HashSet<Order> orders = new HashSet<Order>();

        public HashSet<Order> FriendOrders()
        {
            return orders;
        }

        void AddOrder(Order order)
        {
            order.SetCustomer(this);
        }
    }
/* 단방향 연결 */

class Order
{
   public Customer Customer
  {
   get{
       var customer = Customer.FindCustomer(new CustmerSearchCriteria { Order = this });
      if (customer.Count() < 1 ) throw new Exception("Not Found");
      if (customer.Count() > 1 ) throw new Exception("Multiple customer found for the Order");
      return customer.Single();
    }
  }
}

class Customer
{
  private HashSet<Order> _orders = new HashSet<Order>();
  public HashSet<Order> Orders
  {
      get { return _orders; }
  }
  
  public static IEnumerable<Customer> GetAllCustomer()
  {
      return new List<Customer>();
  }
  
  public static IEnumerable<Customer> FindCustomer(CustomerSearchCriteria order)
  {
      return new List<Customer>();
  }
}

class CustomerSearchCriteria
{
  public Order order { get; set; }
}