Relationship : UML의 Class Diagram

기록하는 용도·2022년 8월 7일
0

Class Diagram 공부와 그에 따른 Java Program을 구성

association, aggregation, composition
association > aggregation > composition

association : use a 관계 
예) 사람이 렌트카를 이용하다
aggregation : has a 관계
예) 고객이 스마트폰을 소유한다.
composition : consist of 관계 
예) 자동차는 엔진과 여러 부품으로 구성된다.
예) 사람을 뇌를 갖고있다. 						

Association

Person
operation: tour()

RentCar
attribute : -model, -price

렌트카는 일시적으로 tour할때만 사용한다. 이때, association관계이다.

Aggregation

customer는 스마트폰 객체를 자신의 인스턴스 변수로 갖고있다.
customer는 스마트폰을 소유하고있다.
스마트폰이 없어도 고객이 존재할수있다.
(스마트폰이 null이거나..)

Composition

조금더 긴밀한 관계 composition
생성자에서 엔진을 만들어버린다.
car의 인스턴스 변수로 엔진이 존재한다는것을 알 수 있다.

Association 예제)


각 메소드에서 실행하고 버리는 관계를 association 관계라고 한다.

이런 표현도 가능하다.

Aggregation 예제)

Aggregation : has a 관계

Customer는 smartPhone을 소유하고있다.
smartPhone이 없으면 Customer는 이를 소유할 수 없다.
Customer가 smartPhone을 소유하기 위해 smartPhone을 먼저 만든다.

has a 관계일 때에는 인스턴스 변수로 저장해 사용한다.

public class Customer {
	private String name;
	// aggregation : has a 관계
	// has a 관계일때는 인스턴스 변수로 저장해 사용한다.
	private SmartPhone smartPhone;
	
	public SmartPhone getSmartPhone() {
		return smartPhone;
	}
	
	public void setSmartPhone(SmartPhone smartPhone) {
		this.smartPhone = smartPhone;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}
  1. Customer 객체를 만들어 이름을 할당함
Customer c = new Customer();
c.setName("장기하");

c.setSmartPhone(new SmartPhone("갤", 100));


smartPhone 객체를 먼저 만들어서(new SmartPhone("갤", 100)) setSmartPhone함수로 인해 Customer에 만든 객체를 할당한다.
객체가 만들어지며 힙 영역에 저장이되고 이 때 여기에 주소값이 생성된다.
결국 Customer 객체의 smartPhone에는 smartPhone 객체의 주소값인 101번지가 저장되는것이다.

aggregation 예제의 경우, "갤", 100의 정보를 갖고있는 smartPhone을 만들어서 "장기하" 고객에다 할당하려는게 setSmartPhone 코드라고 볼 수 있다.

위에 예제를 통해 RentCar는 지역변수로 사용해 메소드가 종료시 없어지는 것을 알 수 있고,
smartPhone은 인스턴스 변수로 사용해 Customer 객체가 없어지지않는 한 유지하는 것을 알 수 있다. (-> Customer 안에 smartPhone이 있는것)

Composition 예제

Engine과 Engine을 소유하는 car만들기

composition : consist of
예) 자동차는 엔진과 바퀴와 같은 요소로 구성된다.
가장 긴밀한 관계라고 볼 수 있다.

public class Car {
	private String model;
	private Engine engine; // composition : consist of 
	
	public Car(String model, String type, int displacement) {
		this.model = model;
		
		//Car 객체 생성시 반드시 Engine 객체를 선행해서 생성하게 강제한다.
		this.engine = new Engine(type, displacement);
	}
}

Car 객체 생성시 반드시 Engine 객체를 선행해서 생성하게 강제한다.
Car 생성의 가장 초기화 -> 힙 영역에 엔진부터 만들어진 후 -> Car 만들어짐
=> Composition
=> 이와 같이 명시함으로써 Car 객체 생성 이전에 Engine 부터 생성하게 된다.

		c.getEngine().setDisplacement(2500);
		System.out.println(c.getEngine().getDisplacement());

c가 참조하는 객체의 엔진의 displacement를 2500으로 변경해본다

0개의 댓글