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

믹시
tistory 티스토리 가입하기!
'java design pattern'에 해당되는 글 3건
2008. 11. 27. 22:21
추상 메소드를 구현하는 것은 하위 클래스이다. 하위 클래스 측에서 메소드를 구현하면 구체적인 처리가 결정된다. 서로 다른 하위 클래스가 서로 다른 구현을 실행하면 서로 다른 처리가 실행될 것입니다. 그러나 하위 클래스에서 어떤 구현을 하더라고 처리의 흐름은 상위 클래스에서 결정한대로 이루어진다.
위와 같이 상위 클래스에서 모든 처리의 흐름을 정의하고, 하위 클래스에서 그 구체적인 내용을 결정하는 패턴이 Template Method 패던이다.

1. AbstractDisplay.java
public abstract class AbstractDisplay {
    public    abstract    void    open();
    public    abstract    void    print();
    public    abstract    void    close();   
    public final void display() {
        open();
        for( int i = 0; i < 5; i++ ) {
            print();
        } close();
    }
}

2. CharDisplay.java
public class CharDisplay extends AbstractDisplay {
    private    char    ch;
    public CharDisplay( char ch ) { this.ch = ch; }   

    public void close() { System.out.println( ">>" ); }
    public void open() { System.out.print( "<<" ); }   
    public void print() { System.out.print( ch ); }   
}

3. StringDisplay.java
public class StringDisplay extends AbstractDisplay {
    private    String    string;
    private    int        width;   
    public StringDisplay( String string ) {
        this.string    = string;
        this.width = string.getBytes().length;
    }
    public void close() { printLine(); }
    public void open() { printLine(); }
    public void print() { System.out.println( "|" + string + "|" ); }
    private void printLine() {
        System.out.print( "+" );
        for( int i = 0; i < width; i++ ) {
            System.out.print( "-" );
        } System.out.println( "+" );
    }
}

4. Main.java
public class Main {
    public static void main(String[] args) {
        AbstractDisplay    d1    = new CharDisplay( 'H' );
        AbstractDisplay d2    = new StringDisplay( "Hello, world." );
        AbstractDisplay d3    = new StringDisplay( "안녕하세요" );
        d1.display();
        d2.display();
        d3.display();
    }
}

어떻게 위의 코드를 보고 금방 이해가 되나여? 저같은 경우에는 앞의 내용들과 크게 다를것은 몬 느끼겠지만 조금씩 다른게 있다는 느낌이 받고 있다.

Template Method패턴을 사용하면 구체적인 알고리즘은 상위 클래스에서 정의대어 있고, 하위 클래스에서는 해당하는 method를 실제로 구현하는 역할을 수행하는 패턴이라고 이해하면 될 것 같다.

:: 그럼 일 글을 읽는 모든 분들에게 오늘 하루 즐겁고 행복하기를 ^^* ::



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를 취급할 수 있다.

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

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



2008. 11. 21. 00:17
지금까지 내가 코딩을 하면서 얼마나 무식하게 코딩을 했는지 요즘 처절하게 느끼고 있다. 팀장님의 코딩 실력과 이사님의 개발자적 시각.. 아주 많이 부족하다는걸 느끼는 가운데 안되겠다 싶어서 공부를 시작한다. 그 첫번째로 패턴...이전에 포스팅에서 얼랭을 공부한다고 했는데 얼랭은 아주 천천히 시간 날때마다 보는 것으로 미루고( 이러면 안되는걸 알면서도 ) 지금당장 공부하는게 급하다!ㅠㅠ;

그 첫번째로 패턴..앞으로 지금 보고 있는 책을 바탕으로 하나하나 패턴에 관해 정리를 해봐야겠다. 이곳에 포스팅 되는 내용은 개인적인 내용도 있고, 지금 보는 책의 내용도 함깨 있음을 미리 밝힌다.

1. Iterator 패턴
모든 언어에서 배열의 요소를 찾기 위해서 for구문과 같은 Loop문을 사용해 요소를 하나하나 찾는다. 이와 같이 첫번째 요소부터 마지막 요소까지 하나하나 찾아 나가는 방법을 일반화한 것이 Iterator 패턴이다. 다시 말해 어떠한 무언가가 모여있는 것들은 단순하게 검색하는 것을 의미한다.

Iterator패턴은 컬랙션 구현 방법을 노출시키지 않으면서도 그 집합체 안에 모요있는 모든 요소에 접근할 수 있게 해주는 방법을 제공한다.

public interface Aggregate { public abstract Iterator iterator(); }

public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

public class Book {
    private String    name;   
    public Book( String name ) { this.name = name; }
    public String getName() { return name; }
}

import java.util.ArrayList;

public class BookShelf implements Aggregate
{
    private    Book[]    books;
    private int        last    = 0;
    private    ArrayList<Book>    arrayList;
   
    public BookShelf() { arrayList    = new ArrayList<Book>(); }
    public BookShelf( int maxsize ) { this.books    = new Book[maxsize]; }
   
    public Book getBookIndex( int index ) {
        return ( arrayList != null ) ? (Book)arrayList.get( index ) : books[index];
    }
    public Book getBookAt( int index ) {
        return ( arrayList != null ) ? arrayList.get( index ) : books[index];
    }
   
    public void appendBook( Book book ) {
        if( arrayList != null )   
            arrayList.add( book );
        else if( arrayList == null && last >= 0 )
        {
            books[last]    = book;       
            last++;
        }
    }
   
    public int getLength() { return ( arrayList != null ) ? arrayList.size() : last; }   
    public Iterator iterator() { return new BookShelfIterator( this ); }
}

public class BookShelfIterator implements Iterator
{
    private    BookShelf    bookShelf;
    private    int            index;
   
    public BookShelfIterator( BookShelf bookShelf ) {
        this.bookShelf    = bookShelf;
        this.index        = 0;
    }
   
    public boolean hasNext() {
        if( index < bookShelf.getLength() ) return true;
        else return false;
    }

    public Object next() {
        Book    book = bookShelf.getBookAt( index );
        index++;       
        return book;
    }
}

위에 상당히 많은 코드들이 보이는데 위 코드들은 서가(BookShelf)안에 책(Book)을 넣고, 그 책의 이름을 차례대로 표시하는 프로그램으로 Size가 정해진 서가와 가변 Slze의 서가가 존재하는 프로그램이다.

public class Main
{
    public static void main(String[] args)
    {
        BookShelf    bookShelf    = new BookShelf( 4 );
        bookShelf.appendBook( new Book( "Around the World in 80 days" ) );
        bookShelf.appendBook( new Book( "Bible" ) );
        bookShelf.appendBook( new Book( "Cinderella" ) );
        bookShelf.appendBook( new Book( "Daddy-Long-Legs" ) );
       
        Iterator    it = bookShelf.iterator();
        while( it.hasNext() )
        {
            Book    book = (Book)it.next();
            System.out.println( book.getName() );
        }
       
        BookShelf    bookShelf2    = new BookShelf();
        bookShelf2.appendBook( new Book( "Around the World in 80 days--" ) );
        bookShelf2.appendBook( new Book( "Bible--" ) );
       
        it = bookShelf2.iterator();
        while( it.hasNext() )
        {
            Book    book = (Book)it.next();
            System.out.println( book.getName() );
        }
    }
}

위 프로그램을 실제 테스트 하는 코드로 첫번째서가는 책을 4권만 넣을 수 있는 서가이지만 아래쪽의 코드는 ArrayList를 사용하는 서가이기 때문에 책의 숫자에 상관없이 저장할 수 있다.

코드들을 보다보면 추상 클랙스, 혹은 인터페이스를 많이 사용한다. 나도 아직 잘 사용해 보지 않은 방식이지만 앞으로 하나씩 보면서 몸에 익혀 보도록 해야겠다.

:: 그럼 이글을 읽는 모든 분들에게 오늘 하루 즐겁고, 행복많이 가득하기를 ::



prev"" #1 next