본문 바로가기
프로그래밍/java

[Java] 더블 디스패치

by 혀끄니 2024. 1. 24.
728x90

Method Dispatch

- 어떤 메소드를 실행할지 결정하는 것

Static Dispatch

- 컴파일되는 시점에 컴파일러가 어떤 클래스의 메소드를 수행하는지 알고 있고 바이트 코드도 남는다.

class Service {
    void run() {
        System.out.println("run()");
    }
}
public static void main(String[] args) {
    new Service().run();
}

 

Dynamic Dispatch

- 어떤 메소드를 실행하는지 컴파일 시점에 모름

- 추상클래스의 메소드를 호출하는 것만 알고 있음

- 런타임 시점에 service에 할당된 객체가 무엇인지 확인하고 메소드를 실행

abstract class Service {
    abstract void run();
}

class ServiceImpl extends Service {
    void run() {
        System.out.println("run()");
    }
}
public static void main(String[] args) {
    Service service = new ServiceImpl();
    service.run();
}

Double Dispatch

- Dynamic Dispatch를 두번 하는것

- Post중 어떤 구현체의 postOn메소드를 실행할지 Dynamin Dispatch한번사용

- postOn메소드 내부에서 SNS중 어떤 구현체의 post메소드를 실행할지 Dynamic Dispatch한번 사용

interface Post {
    void postOn(SNS sns);
}

class Text implements Post {
    public void postOn(SNS sns) {
        sns.post(this);
    }
}

class Picture implements Post {
    public void postOn(SNS sns) {
        sns.post(this);
    }
}
interface SNS {
    void post(Text text);
    void post(Picture picture);
}

class Facebook implements SNS {
    public void post(Text text) {
        // text -> facebook
    }
    public void post(Picture picture) {
        // picture -> facebook
    }
}

class Twitter implements SNS {
    public void post(Text text) {
        // text -> twitter
    }
    public void post(Picture picture) {
        // picture -> twitter
    }
}
    public static void main(String[] args) {
        List<Post> posts = Arrays.asList(new Text(), new Picture());
        List<SNS> sns = Arrays.asList(new Facebook(), new Twitter());

        posts.forEach(p -> sns.forEach(s -> p.postOn(s)));
    }
728x90

'프로그래밍 > java' 카테고리의 다른 글

[Java][api] 공공데이터 - 기상청단기예보  (1) 2024.01.26
[Java] 실행 인코딩 설정  (0) 2024.01.25
[Java] Servlet - 2  (0) 2024.01.23
[Java] Servlet - 1  (0) 2024.01.22
[Java][Netty] Codec  (0) 2024.01.19