DESIGN PATTERN/실용주의 디자인패턴

Chapter 4- Strategy 패턴

파란실버라이트 2013. 1. 8. 10:41

 

기본 아이디어

Strategy 패턴에서는 문제를 해결하여 여러 알고리즘이 존재할 경우 각 알고리즘을 별도의 클래스로 캡슐화하고, 이를 상호 교환 가능하도록 한다. 이때 각 알고리즘을 갭슐화한 클래스들(Concrete Strategy)은 알고리즘에 접속할 수 있는 인터페이스(Strategy)를 구현한다. 알고리즘을 사용하는 클라이언트(Context)는 Stategy 인터페이스를 통해 Concrete Strategy를 사용한다.

 

 

 

 

 

interface Selector
{
boolean approve( Cursor[] rows );


void modify( Cursor current );


public static class Adapter implements Selector
{

public boolean approve( Cursor[] tables )
{

return true;
}
public void modify( Cursor current )
{

throw new UnsupportedOperationException(
"Can't use a Selector.Adapter in an update");
}
}


public static final Selector ALL = new Selector.Adapter();

}

<Selector.Adapter를 확장>

 

people.delete ( new Selector.Adapter()
{

public boolean approve( Cursor[] tables )
{

 return tables[0].column("lastName").equals("Flintstone");

}

}

 

- Table에 어떤 로우를 선택해야 하는지를 알고 있는 객체를 넘기는 것이다.

   Selector가 바로 선택 전략을 캡슐화하고 있다.

- Delete() 메소드는 Strategy 객체의 approve() 메소드를 각 로우마다 호출

- Approve() 메소드는 해당로우가 삭제되어야 하는지에 대한 Boolean 값을 반환

 

   

<Selector 인터페이스를 직접 구현>

 

   address.update
    (     new Selector()
            {

public boolean approve( Cursor[] tables )
{

      return tables[0].column("state").equals("AZ");
}
public void modify( Cursor current )
{

       current.update("state", "AZ");
}

}

);

 

- 갱신 연산도 삭제와 동일한 방식으로 동작하지만 Selection의 approve() 메소드뿐 아니라 modify() 메소드도 오버라이딩해야

  한다는 점이 다르다.

 

<Concete Table에서 Strategy 객체(Selector)를 사용 하는 코드>

public int  update( Selector where )
 { 
      Results  currentRow = (Results)rows();
      Cursor[] envelope  = new Cursor[]{ currentRow };
      int   updated = 0;

  while( currentRow.advance() )
  { 

    if( where.approve(envelope) )
   { 

        where.modify(currentRow);
        ++updated;
   }
  }

  return updated;
 }


 //----------------------------------------------------------------------
 public int  delete( Selector where )
 { 

     int deleted = 0;

     Results  currentRow = (Results) rows();
     Cursor[] envelope = new Cursor[]{ currentRow };

   

     while( currentRow.advance() )
    { 

        if( where.approve( envelope) )
        { 

            currentRow.delete();
            ++deleted;

         }
  }
      return deleted;
 }

 

- Update()와 Delete()가 하는 일은 순회 코드를 감추고 적절한 Strategy 객체(Selector)를 호출 하는 것이다.

- 이 코드는 또한 Passive Iterator의 변형형을 보여준다. 순회알고리즘은 Concrete Table안에 있으므로

   Selector는 Table 객체들은 순회하는 Passive Iterator라고 할 수 있다.