발전하는 나를 기록하기 위해

Association(연관), Aggregation(집합), Composition(구성) 본문

개발/Java

Association(연관), Aggregation(집합), Composition(구성)

발폼도래 2024. 3. 5. 16:07
728x90

 

/**  
 * Association (연관):  
 * Association은 클래스 간의 관계를 표현하는 가장 기본적인 형태입니다.   
 * 서로 다른 클래스들이 연결되어 상호작용하는 것을 의미합니다.   
 * 아래는 Student 클래스와 Course 클래스 간의 Association 예제입니다.  
 */
 public class Student {  
    private String name;  
    public Student(String name) {        this.name = name;    }  
    public void enrollCourse(Course course) {       
          // 학생이 수강할 과목에 등록하는 로직  
    }}  
  
public class Course {  
    private String name;  
    public Course(String name) {        this.name = name;    }}  
  
public class Main {  
    public static void main(String[] args) {        
        Student student = new Student("Alice");        
        Course course = new Course("Math");        
        student.enrollCourse(course);    }}  
  
/**  
 * Aggregation (집합):  
 * Aggregation은 한 객체가 다른 객체를 포함하고 있는 관계를 나타냅니다.   
 * 하나의 객체가 다른 객체를 소유하고 있지만, 객체들 간에 라이프사이클의 종속성이 없는 관계입니다.   
 * 아래는 University 클래스와 Department 클래스 간의 Aggregation 예제입니다.  
 */
 public class University {  
    private List<Department> departments;  
    public University() {        this.departments = new ArrayList<>();    }  
    public void addDepartment(Department department) {        departments.add(department);    }}  
  
public class Department {  
    private String name;  
    public Department(String name) {        this.name = name;    }}  
  
public class Main {  
    public static void main(String[] args) {        University university = new University();        Department department = new Department("Computer Science");        university.addDepartment(department);    }}  
  
/**  
 * Composition (구성):  
 * Composition은 한 객체가 다른 객체를 포함하면서 라이프사이클의 종속성이 있는 관계를 나타냅니다.   
 * 한 객체의 생성과 소멸이 다른 객체에 직접적으로 영향을 미치는 관계입니다.   
 * 아래는 Car 클래스와 Engine 클래스 간의 Composition 예제입니다.  
 */
 public class Car {  
    private Engine engine;  
    public Car() {        this.engine = new Engine();    }}  
  
public class Engine {  
    public Engine() {        
        // 엔진 객체의 초기화 로직  
    }}  
  
public class Main {  
    public static void main(String[] args) {        
        Car car = new Car();        // car 객체 생성 시 Engine 객체도 함께 생성됨  
    }}  

'개발 > Java' 카테고리의 다른 글

ClassLoader 상대경로 파일읽기  (0) 2024.03.27
java stream  (0) 2024.03.14