DevCastleOne

 

 

※ Static Dispatch란?

: 컴파일 시점에 컴파일러가 어떤 클래스의 메소드를 실행해야하는지 알고 바이트코드로도 남는다.

(참고로 메소드 오버로딩의 경우 static dispatch를 사용한다.)

 

public class Dispatch{

    public void run(){
        System.out.println("run");
    }

    public static void main(String[] args) {
        new Dispatch().run();
    }

}

 

※ Dynamic Dispatch란?

 

: 컴파일 시점에선 어떤 메소드를 호출하는지 모른다. 추상 타입의 메소드를 호출하는것만 알고 있음.

: 런타임 시점에 할당된 객체의 타입을 보고 메소드를 실행함.

 

public class Dispatch{

    static abstract class Service{
        abstract void run();
    }

    static class ServiceTest extends Service{
        @Override
        void run() {
            System.out.println("ServiceTest run");
        }
    }

    public static void main(String[] args) {
        Service svc = new ServiceTest();
        svc.run();
    }

}

 

# Double Dispatch란?

 

: Dynamic Dispatch를 두번 하는것

 

public class Dispatch {
    interface Post {
        void postOn(SNS sns);
    }
    static class Text implements Post{
        @Override
        public void postOn(SNS sns) {
            sns.post(this);
        }
    }
    static class Picture implements Post{
        @Override
        public void postOn(SNS sns) {
            sns.post(this);
        }
    }

    interface SNS{
        void post(Text post);
        void post(Picture post);
    }
    static class Facebook implements SNS{

        @Override
        public void post(Text post) {
            System.out.println("text-facebook");
        }

        @Override
        public void post(Picture post) {
            System.out.println("picture-facebook");
        }
    };
    static class Twitter implements SNS{

        @Override
        public void post(Text post) {
            System.out.println("text-twitter");
        }

        @Override
        public void post(Picture post) {
            System.out.println("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)));
    }
}

=====================결과=====================
text-facebook
text-twitter
picture-facebook
picture-twitter

 

 

1. Post 클래스 구현체중 어떤 클래스의 postOn 메소드를 사용할지  (Dynamic Dispatch 한번 사용)

2. postOn에 인자로 선택된에서(SNS로 구현된 클래스) 어떤 post 메소드를 사용할지 (Dynamic Dispatch 한번 사용)

 

두번의 Dynamic Dispatch가 사용됨!!

 

 

참고)

토비님의 유튜브 강의

 

'JAVA' 카테고리의 다른 글

JAVA] 예외처리 하는 방법  (0) 2021.01.15
[JAVA] 자바 패키지란?  (0) 2020.12.30
자바 상속이란?  (0) 2020.12.25
[JAVA] 클래스란?  (0) 2020.12.16
Java13 switch 연산자  (0) 2020.11.28

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band