Hello, Freakin world!

[채팅앱][클라이언트] SelectorManager 클래스 작성하기 본문

Toy Project/채팅 앱 만들기

[채팅앱][클라이언트] SelectorManager 클래스 작성하기

johnna_endure 2020. 2. 27. 05:34
import ...

public class SelectorManager {
    Selector selector;
    
    public synchronized Selector getSelector(){
        if(!selector.isOpen() | selector == null ) {
            open();
            return selector;
        }
        return selector;
    }

    public void close(){
        try {
            selector.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void open() {
        try {
            selector = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

매니저 객체는 getSelector() 메서드를 통해 selector 객체를 반환하며, 내부에서 생성된 하나의 객체만을 반환한다.

 

단위 테스트까지 작성해두자.

public class TestSelectorManager {
    SelectorManager manager;

    @Before
    public void before() {
        manager = new SelectorManager();
    }
    @Test
    public void testGetSelector_returnOpenedSelectorWhenFirstInvoking() {
        assertThat(manager.getOpenSelector().isOpen()).isTrue();
    }

    @Test
    public void testGetSelector_returnOpenedSelectorAfterClose(){
        Selector selector = manager.getOpenSelector();
        manager.close();
        assertThat(manager.getOpenSelector().isOpen()).isTrue();
    }
}
Comments