분류 전체보기 (199)
ººº::Development™:: (66)
ººº::Learning™:: (31)
ººº::Information™:: (37)
ººº::Note™:: (11)
ººº::Photo™:: (50)
ººº::zEtc™:: (3)
rss

믹시
tistory 티스토리 가입하기!
2008. 11. 27. 21:47
우리가 일사 생활에서 10v를 사용하는 전자 제품에 220볼트의 전원을 연결할 때, 중간에 어뎁터라는 것을 사용해서 전류를 변화 시켜주는 거와 같이 Adapter패턴은 한 클래스의 인터페이스를 다른 인터페이스로 변환해 주는 패턴입니다. Adapter패턴을 사용하면 인터페이스 호환성 문제 때문에 같이 사용할 수 없는 클래스를 연결해 줍니다.

아래 예제는 java.util의 Properties 클래스를 사용해 peorperty를 스크림에서 읽고 해당 property내용을 업데이트 한 후 다시 스크림을 쓰는 Adapter Class인 FileProperties Class를 작성하는 것이다.

1. FileIO.java
import java.io.IOException;

public interface FileIO
{
    public    void    readFromFile( String fileName ) throws IOException;
    public    void    writeToFile( String fileName ) throws IOException;
    public    void    setValue( String key, String value );
    public    String    getValue( String key );
}

2. FileProperties.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class FileProperties extends Properties implements FileIO
{
    Properties properties = new Properties();

    @Override
    public String getValue( String key ) { return properties.getProperty( key ); }

    @Override
    public void readFromFile(String fileName) throws IOException {
        properties.load( new FileInputStream( fileName ) );
    }

    @Override
    public void setValue(String key, String value) { properties.setProperty( key, value ); }

    @Override
    public void writeToFile(String fileName) throws IOException {
        properties.store( new FileOutputStream( fileName ), "Written by FileProperties" );
    }
}


3. Main.java
import java.io.IOException;

public class Main {
    public static void main( String[] args ) {
        FileIO    f    = new FileProperties();
        try
        {
            f.readFromFile( "file.txt" );
            f.setValue( "year", "2004" );
            f.setValue( "month", "4" );
            f.setValue( "day", "21" );
            f.writeToFile( "newfile.txt" );
        } catch( IOException e ) { e.printStackTrace(); }
    }
}


아직 이 패턴이 어떻게 쓰이는지는 잘 모르겠지만 전혀 이질적인 인터페이스를 가지는 클래스를 연결할 때, 사용하면 유용할 꺼 같기는 하다. 위 예지를 보면 FileIO Class 만 알고 있다면, FileProperties클래스가 Properties클래스의 메소르에 대해서 몰라고 peroperty를 취급할 수 있다.

정말로 어럽다.. 언제 다 이해를 할 수 있을런지!ㅡㅡ;

:: 이 글을 읽는 모든 분들에게 오늘 하루 즐겁고 행복만이 가득 하기를..^^*; ::