8.9(목) C++ - 예외이야기

from Study/C++ 2007/08/12 21:19 view 20902

#include <iostream>

using namespace std;

 

// 예외이야기- 진짜 예외는 객체를(클래스) 만들어서 계층화 해야 한다.

// 예상치 않은 에러가 난다면 설계가 잘못된 것.(사용자가 지정하지 않은 에러)

// 롤백- 예외 발생시 다시 안전된 상태로 돌려놔야 한다.

 

class Exception {};

class StackException : public Exception {};

class StackUnderflowException : public StackException {};

 

// 예외 안전성의 개념

// 1. 기본보장: 예외 처리후 메모리등의 리소스낭비는 없지만 프로그램의 상태를 알
                        수는 없다
.

// 2. 강력보장: 예외를 처리한 후 프로그램의 상태가 예외발생 이전으로 복구된다.

// 3. 완전보장: 예외가없다. int a = 10;

 

// 예외중립( Exception neutral )

// exceptional c++
http://cafe.naver.com/cppmaster/1516


class
Test

{

       int buf[100];

public:

       Test() { throw 1; }

};

 

void main()

{

       try

       {

       Test* p = new Test; // 1. 메모리할당

                           // 2. 생성자호출- 그런데예외가나왔다.

       // (1)에서 할당한 메모리는 해지되었을까?? 낭비인가??

       // new 자체에서 에러 발생시 낭비를 방지하는 코드가 있다.

       }

       catch( int )

       {

       }

}

 

void foo() // 어떠한 예외라도 나올 수 있다. 예외가 없다는 throw()를 붙여줘야 한다.

{

       try

       {

             char* p = new char;

       }

       catch( std::bad_alloc e )

       {

             // 어떻게 처리할까?

             // 1. 메모리를 재할당해서 성공할 수 있다면 ok.

             // 2. 그렇지 않다면 호출자에게 다시 전달.. - 예외중립

             throw;

       }

}

 

//////////////////////////////////////////////////////////////////

// 아래 대입 연산자가 예외안전성을 지원하는가?

class String

{

       char* buff;

       int sz;

public:

 

       String& operator=( const String& s )

       {

             if ( &s == this ) return *this;

            

             char* temp = new char[ s.sz+1 ]; // 예외가 발생 할 수도 있다.

 

             strcpy( buff, s.buff );

 

             // 예외가 발생하지 않는 코드(강력보장)는 나중에 수행하자.

             delete[] buff;      // 예외가 없다.

             buff = temp;

             sz = s.sz;          // 예외가 없다.

 

             return *this;

       }

};

 

void main()

{

       String s1 = "hello";

       String s2 = "A";

 

       try

       {

             s1 = s2;

       }

       catch ( ... )

       {

       }

 

       cout << s1 << endl;   // 'A' 또는'hello" 가나와야한다.

}

 

class Stack

{

       int buf[10];

       int top;

public:

 

       int Pop() throw( StackUnderflowException )

       {

             if ( top < 0 )

             {

                    throw StackUnderflowException();

             }

             return buf[--top];

       }

};

 

void main()

{

       Stack s;

       try

       {

             int n = s.Pop();

       }

       catch( StackUnderflowException e )

       {

             cout << "예외처리" << endl;

       }

       // 예외를 잡아서 문제를 처리했다. 이제 stack을 계속 사용할 수 있을까?

       s.Push(10);

}

 

Tag |

// 방문자( Visitor )를 적용한 버전.

// Accepter가 있어야 한다.

 

#include <iostream>

#include <conio.h>

#include <string>

#include <vector>

using namespace std;

 

#define clrscr()    system("cls")

 

// Acceptor 인터페이스- 모든 방문자를 받아 들일수 있어야 한다.

class IVisitor;

 

struct IAcceptor

{

       virtual void accept( IVisitor* p ) = 0;

};

 

// Visitor 인터페이스- 방문 할수 있어야 한다.

struct IVisitor

{

       virtual void visit( IAcceptor* p ) = 0;

};

 

class AbstractMenu : public IAcceptor

{

       string title;

public:

       AbstractMenu( string s ) : title(s) { }

 

       virtual string GetTitle() const { return title; }

 

       virtual void SetTitle( string s ) { title = s; }

 

       virtual void Command() = 0; // 순수가상함수- 자식은 꼭 만들어야 한다.

 

       virtual void accept( IVisitor* p )

       {

             p->visit( this );          // Visitor 설계의 핵심

       }

};

 

class PopupMenu : public AbstractMenu

{

       vector<AbstractMenu*> menu_list; // Composite

public:

       PopupMenu(string s) : AbstractMenu(s) { }

 

       void Add( AbstractMenu* p ) { menu_list.push_back( p ); }

       void Remove() { }

 

       virtual string GetTitle() const

       {

             return string("[") + AbstractMenu::GetTitle() + string("]");

       }

 

       // 팝업 메뉴가 선택되었을때를 처리한다.

       virtual void Command()

       {

             while(1)

             {

                    // 화면을지우고자신의하위메뉴를열거해준다.

                    clrscr();

 

                    for( int i = 0; i < menu_list.size(); ++i )

                    {

                        cout << i+1 <<"."<< menu_list[i]->GetTitle() <<endl;

                    }

 

                    cout << menu_list.size() + 1 << ". 이전메뉴로" << endl;

                    //------------------------------------------------

                    int cmd;

                    cout << "메뉴를생성하세요>> ";

                    cin >> cmd;

 

                    if ( cmd == menu_list.size()+1 ) // 이전메뉴로 선택

                           break;  // 루프 탈출해서 자신을 이 함수를 마치고

                                   // 자신을 호출한 부분으로 돌아간다.

 

                    // 잘못 선택한 경우
                   
if ( cmd <= 0 || cmd > menu_list.size() )    

                           continue;

 

                    // 해당 메뉴를 실행한다.

                    menu_list[cmd-1]->Command();

             }

       }

 

       // 팝업 메뉴의 경우 모든 항목에 대해 visit를 호출해야 한다.

       virtual void accept( IVisitor* p )

       {

             p->visit( this );   // 먼저 자신을 보내고

            

             for( int i = 0; i < menu_list.size(); ++i )

                    menu_list[i]->accept( p );

       }

};

 

// 메뉴를 처리하고 싶은 모든 클래스는 아래 인터페이스를 구현해야 한다.

struct IMenuHandler

{

       virtual void MenuCommand( int id ) = 0;

};

 

class MenuItem : public AbstractMenu

{

       int id;

       IMenuHandler* pMenuHandler;

public:

       // 부모의 디폴트 생성자가 없으므로 여기서 초기화 해준다.

       MenuItem( string s, int n, IMenuHandler* p )

             : AbstractMenu(s), id(n), pMenuHandler(p) { }

 

       // 메뉴 선택시 처리

       virtual void Command()

       {

             if( pMenuHandler != 0 ) pMenuHandler->MenuCommand( id );

       }

};

 

// 메뉴의 각 항목의 색상을 변경하는 visitor

class RedVisitor : public IVisitor

{

public:

       virtual void visit( IAcceptor* p )

       {

             AbstractMenu* pMenu = (AbstractMenu*)p;

 

             string s = pMenu->GetTitle();

 

             s = s + string("-Red");

 

             pMenu->SetTitle( s );

       }

};

 

//------------------------------------------------------

class VideoShop : public IMenuHandler

{

public:

       void Init()

       {

             PopupMenu* p1 = new PopupMenu("ROOT");

 

             PopupMenu* p2 = new PopupMenu("고객관리");

             PopupMenu* p3 = new PopupMenu("Tape관리");

             PopupMenu* p4 = new PopupMenu("기타");

 

             p1->Add( p2 );

             p1->Add( p3 );

             p1->Add( p4 );

 

             p2->Add( new MenuItem("신규고객등록", 1, this) );

             p2->Add( new MenuItem("고객삭제", 2, this) );

             p2->Add( new MenuItem("기타", 3, this) );

 

             p3->Add( new MenuItem("신규Tape등록", 4, this) );

             p3->Add( new MenuItem("Tape삭제", 5, this) );

             p3->Add( new MenuItem("기타", 6, this) );

 

             RedVisitor r;

             p1->accept(&r);

 

             p1->Command();

       }

 

       void AddCustomer()

       {

             cout << "신규고객등록처리" << endl;

       }

 

       virtual void MenuCommand( int id )

       {

             // 메뉴 ID를 가지고 각 함수로 라우팅 한다.

             if ( id == 1 ) AddCustomer();

 

             cout << "다른ID처리" << endl;

             getch();

       }

};

 

int main()

{

       VideoShop v;

       v.Init();

}

Tag | ,

// 책임의 전가- Chain of reponsibility

// MFCVIEW- DOC - FRAME - APP 로 명령을 넘겨주는 것과 같은 원리..

 

#include <iostream>

#include <conio.h>

#include <string>

#include <vector>

using namespace std;

 

// 메뉴를 처리하고 싶은 모든 클래스는 아래 추상클래스에서 상속되어야 한다.

class IMenuHandler

{

       IMenuHandler* next;

public:

       IMenuHandler() : next(0) {}

 

       // 다음 처리할 객체를 지정한다.

       void SetNext( IMenuHandler* p ) { next = p; }

 

    void MenuCommand( int id )

       {

             // 먼저 자신이 처리를 시동한다.

             if ( Resolve( id ) == false ) // 처리를 못한 경우

             {

                    // 다음으로전달
                   
if ( next != 0 ) next->MenuCommand( id );

             }

       }

protected:

       virtual bool Resolve( int id ) = 0;

};

//-------------------------------------------------------

 

#define clrscr()    system("cls")

 

class AbstractMenu

{

       string title;

public:

       AbstractMenu( string s ) : title(s) { }

 

       virtual string GetTitle() const { return title; }

 

       virtual void Command() = 0;   // 순수가상함수- 자식은 꼭 만들어야 한다.

};

 

class PopupMenu : public AbstractMenu

{

       vector<AbstractMenu*> menu_list; // Composite

public:

       PopupMenu(string s) : AbstractMenu(s) { }

 

       void Add( AbstractMenu* p ) { menu_list.push_back( p ); }

       void Remove() { }
 

       virtual string GetTitle() const

       {

             return string("[") + AbstractMenu::GetTitle() + string("]");

       }

 

       // 팝업메뉴가 선택 되었을때를 처리한다.

       virtual void Command()

       {

             while(1)

             {

                    // 화면을 지우고 자신의 하위메뉴를 열거해준다.

                    clrscr();

 

                    for( int i = 0; i < menu_list.size(); ++i )

                    {

                         cout<<i + 1<<"."<< menu_list[i]->GetTitle() <<endl;

                    }

 

                    cout << menu_list.size() + 1 << ". 이전메뉴로" << endl;

                    //-----------------------------------------------

                    int cmd;

                    cout << "메뉴를 생성하세요>> ";

                    cin >> cmd;

 

                    if ( cmd == menu_list.size()+1 ) // 이전메뉴로 선택

                           break;  // 루프탈출해서 자신을 이 함수를  마치고

                                   // 자신을 호출한 부분으로 돌아간다.

                    // 잘못선택한경우

                    if ( cmd <= 0 || cmd > menu_list.size() )    

                           continue;

 

                    // 해당메뉴를 실행한다.

                    menu_list[cmd-1]->Command();

             }

       }

};

 

// 메뉴를 처리하고 싶은 모든 클래스는 아래 인터페이스를 구현해야 한다.

class MenuItem : public AbstractMenu

{

       int id;

       IMenuHandler* pMenuHandler;

public:

       // 부모의 디폴트 생성자가 없으므로 여기서 초기화 해준다.

       MenuItem( string s, int n, IMenuHandler* p )

             : AbstractMenu(s), id(n), pMenuHandler(p) { }

 

       // 메뉴선택시 처리

       virtual void Command()

       {

             if( pMenuHandler != 0 ) pMenuHandler->MenuCommand( id );

       }

};

//------------------------------------------------------

class TapeList : public IMenuHandler

{

public:

       virtual bool Resolve( int id )

       {

             switch( id )

             {

             case 1: foo(); getch(); return true;

             case 2: foo(); getch(); return true;

             }

             return false;

       }

 

       void foo()

       {

             cout << "TapeList::foo" << endl;

       }

};

 

//-----------------------------------------------------

class VideoShop : public IMenuHandler

{

       TapeList tp_list;

 

public:

       void Init()

       {

             PopupMenu* p1 = new PopupMenu("ROOT");

 

             PopupMenu* p2 = new PopupMenu("고객관리");

             PopupMenu* p3 = new PopupMenu("Tape관리");

             PopupMenu* p4 = new PopupMenu("기타");

 

             p1->Add( p2 );

             p1->Add( p3 );

             p1->Add( p4 );

 

             p2->Add( new MenuItem("신규고객등록", 1, this) );

             p2->Add( new MenuItem("고객삭제", 2, this) );

             p2->Add( new MenuItem("기타", 3, this) );

 

             p3->Add( new MenuItem("신규Tape등록", 4, this) );

             p3->Add( new MenuItem("Tape삭제", 5, this) );

             p3->Add( new MenuItem("기타", 6, this) );

 

             // 메뉴를 처리하고 싶은 다음 객체를 등록시킨다.

             this->SetNext( &tp_list );

 

             p1->Command();

       }

 

       void AddCustomer()

       {

             cout << "신규고객등록처리" << endl;

       }

 

       virtual void MenuCommand( int id )

       {

             // 메뉴ID를 가지고 각 함수로 라우팅한다.

             if ( id == 1 ) AddCustomer();

 

             cout << "다른ID처리" << endl;

             getch();

       }

 

       virtual bool Resolve( int id )

       {

             if ( id == 1 )

             {

                    AddCustomer();

                    return true;

             }

             return false;

       }

};

 

 

int main()

{

       VideoShop v;

       v.Init();

}

Tag | ,

#include <iostream>

#include <conio.h>

#include <string>

#include <vector>

using namespace std;

 

#define clrscr()    system("cls")

 

class AbstractMenu

{

       string title;

public:

       AbstractMenu( string s ) : title(s) { }

 

       virtual string GetTitle() const { return title; }

 

       virtual void Command() = 0; // 순수가상함수- 자식은 꼭 만들어야 한다.

};

 

class PopupMenu : public AbstractMenu

{

       vector<AbstractMenu*> menu_list; // Composite

public:

       PopupMenu(string s) : AbstractMenu(s) { }

 

       void Add( AbstractMenu* p ) { menu_list.push_back( p ); }

       void Remove() {}

 

       virtual string GetTitle() const

       {

             return string("[") + AbstractMenu::GetTitle() + string("]");

       }

 

       // 팝업메뉴가 선택 되었을때를 처리한다.

       virtual void Command()

       {

             while(1)

             {

                    // 화면을 지우고 자신의 하위메뉴를 열거 해준다.

                    clrscr();

 

                    for( int i = 0; i < menu_list.size(); ++i )

                    {

                           cout << i + 1 << "." << menu_list[i]->GetTitle() << endl;

                    }

 

                    cout << menu_list.size() + 1 << ". 이전메뉴로" << endl;

                    //---------------------------------------------------------

                    int cmd;

                    cout << "메뉴를생성하세요>> ";

                    cin >> cmd;

 

                    if ( cmd == menu_list.size()+1 ) // 이전메뉴로 선택

                           break;  // 루프 탈출해서 자신을 이함수를 마치고

                                   // 자신을 호출한 부분으로 돌아간다.

                    // 잘못 선택한 경우

                    if ( cmd <= 0 || cmd > menu_list.size() )
                           continue;

 

                    // 해당메뉴를 실행한다.;;

                    menu_list[cmd-1]->Command();

             }

       }

};

 

// 메뉴를 처리하고 싶은 모든 클래스는 아래 인터페이스를 구현해야 한다.

struct IMenuHandler

{

       virtual void MenuCommand( int id ) = 0;

};

 

class MenuItem : public AbstractMenu

{

       int id;

       IMenuHandler* pMenuHandler;

public:

       // 부모의 디폴트 생성자가 없으므로 여기서 초기화 해준다.

       MenuItem( string s, int n, IMenuHandler* p )

             : AbstractMenu(s), id(n), pMenuHandler(p) { }

 

       // 메뉴선택시 처리

       virtual void Command()

       {

             if( pMenuHandler != 0 ) pMenuHandler->MenuCommand( id );

       }

};

//------------------------------------------------------

class VideoShop : public IMenuHandler

{

public:

       void Init()

       {

             PopupMenu* p1 = new PopupMenu("ROOT");

 

             PopupMenu* p2 = new PopupMenu("고객관리");

             PopupMenu* p3 = new PopupMenu("Tape관리");

             PopupMenu* p4 = new PopupMenu("기타");

 

             p1->Add( p2 );

             p1->Add( p3 );

             p1->Add( p4 );

 

             p2->Add( new MenuItem("신규고객등록", 1, this) );

             p2->Add( new MenuItem("고객삭제", 2, this) );

             p2->Add( new MenuItem("기타", 3, this) );

 

             p3->Add( new MenuItem("신규Tape등록", 4, this) );

             p3->Add( new MenuItem("Tape삭제", 5, this) );

             p3->Add( new MenuItem("기타", 6, this) );

 

             p1->Command();

       }

 

       void AddCustomer()

       {

             cout << "신규고객등록처리" << endl;

       }

 

       virtual void MenuCommand( int id )

       {

             // 메뉴ID를 가지고 각 함수로 라우팅한다.

             if ( id == 1 ) AddCustomer();

 

             cout << "다른ID처리" << endl;

             getch();

       }

};

 

 

int main()

{

       VideoShop v;

       v.Init();

}

 

Tag | ,

8.8(수) C++ 디자인패턴 - Callback

from Study/C++ 2007/08/12 19:53 view 24626

// Callback의 개념.


class Car

{

       typedef void(*SIGNAL)();

       SIGNAL signal;

public:

       Car(SIGNAL s = 0) : signal(s) { }

 

       void SpeedUp( int speed )

       {

             cout << "Speed : " << speed << endl;

 

             if( speed > 100 && signal != 0 )

                    signal();    // 외부에알린다.

       }

};

 

void Police()

{

       cout << "Police Start.." << endl;

}

 

void main()

{

       Car c(Police);

 

       c.SpeedUp(100);

       c.SpeedUp(200);

}

/////////////////////////////////////////////////////////////

// 1. callback을 담당 할 클래스를 만들자. - 함수포인터를 관리하는 객체

class delegate

{

       typedef void(*SIGNAL)();

 

       SIGNAL signal;

       vector<delegate*> del_list;

public:

       delegate( SIGNAL s ) : signal(s) {}

 

       void Add( delegate* p ) { del_list.push_back( p ); }

       void Remove( delegate* p ) { }

      

       void Invoke()

       {

             if( signal != 0 ) signal();

 

             for( int i = 0; i < del_list.size(); ++i )

                    del_list[i]->Invoke();

       }

       // 연산자 재정의

       delegate* operator+=(delegate* p)

       {

             Add(p);

             return this;

       }

 

       void operator()()

       {

             Invoke();

       }

};

//----------------------------------------------------------

 

void foo() { cout << "foo" << endl; }

 

void main()

{

       delegate d1(foo);

       delegate d2(foo);

       delegate d3(foo);

 

       d3 += new delegate(foo);

       d3.Add( new delegate(foo) );

 

       d2 += &d3;

       d1.Add( &d2 );

 

       d1.Invoke();

       cout << endl;

       d1();

}

/////////////////////////////////////////////////////////////////
// 2. callback을 담당 할 클래스를 만들자. - 함수포인터를 관리하는 객체

class delegate

{

       typedef void(*SIGNAL)();

 

       SIGNAL signal;

       vector<delegate*> del_list;

public:

       delegate( SIGNAL s ) : signal(s) {}

 

       void Add( delegate* p ) { del_list.push_back( p ); }

       void Remove( delegate* p ) { }

      

       void Invoke()

       {

             if( signal != 0 ) signal();

 

             for( int i = 0; i < del_list.size(); ++i )

                    del_list[i]->Invoke();

       }

       // 연산자재정의

       delegate* operator+=(delegate* p)

       {

             Add(p);

             return this;

       }

 

       void operator()()

       {

             Invoke();

       }

};

//----------------------------------------------------------

class Car

{

public:

       delegate del;

public:

       Car() : del(0) { }

 

       void SpeedUp( int speed )

       {

             cout << "Speed : " << speed << endl;

 

             if( speed > 100  /*&& del != 0*/ )

                    del(); // 외부에알린다.

       }

};

 

void Police()

{

       cout << "Police Start.." << endl;

}

 

void main()

{

       Car c;

 

       c.del += new delegate(Police);

       c.del += new delegate(Police);

 

       c.SpeedUp(100);

       c.SpeedUp(200);

}

 

 

 

 

 

Tag | ,

#include <iostream>

#include <conio.h>

#include <string>

#include <vector>

using namespace std;

 

#define clrscr()       system("cls")

 

class AbstractMenu

{

        string title;

public:

        AbstractMenu( string s ) : title(s) { }

 

        virtual string GetTitle() const { return title; }

 

        virtual void Command() = 0;   // 순수가상함수- 자식은 꼭 만들어야 한다.

};

 

class MenuItem : public AbstractMenu

{

        int id;

public:

        // 부모의 디폴트 생성자가 없으므로 여기서 초기화 해준다.

        MenuItem( string s, int n ) : AbstractMenu(s), id(n) { }    

 

        // 메뉴 선택시 처리

        virtual void Command()

        {

               cout << "MenuItem::Command" << endl;

               getch();

        }

};

 

class PopupMenu : public AbstractMenu

{

        vector<AbstractMenu*> menu_list;      // Composite

public:

        PopupMenu(string s) : AbstractMenu(s) { }

 

        void Add( AbstractMenu* p ) { menu_list.push_back( p ); }

        void Remove() { }      // 나중에 구현.

 

        virtual string GetTitle() const

        {

               return string("[") + AbstractMenu::GetTitle() + string("]");

        }

 

        // 팝업 메뉴가 선택 되었을 때를 처리한다.

        virtual void Command()

        {

               while(1)

               {

                       // 화면을 지우고 자신의 하위메뉴를 열거해준다.

                       clrscr();

 

                       for( int i = 0; i < menu_list.size(); ++i )

                       {

                              cout << i + 1 << "." <<
                                           menu_list[i]->GetTitle() << endl;

                       }

 

                       cout << menu_list.size() + 1 << ". 이전메뉴로" << endl;

                       //-------------------------------------------

                       int cmd;

                       cout << "메뉴를 생성하세요>> ";

                       cin >> cmd;

 

                       if ( cmd == menu_list.size()+1 ) // 이전 메뉴로 선택

                              break; // return; 루프 탈출해서 이함수를 마치고

                                     // 자신을 호출한 부분으로 돌아간다.

 

                       // 잘못 선택한 경우
                      
if ( cmd <= 0 || cmd > menu_list.size() )

                              continue;

 

                       // 해당 메뉴를 실행한다.

                       menu_list[cmd-1]->Command();

               }

        }

};

 

int main()

{

        PopupMenu* p1 = new PopupMenu("ROOT");

 

        PopupMenu* p2 = new PopupMenu("고객관리");

        PopupMenu* p3 = new PopupMenu("Tape관리");

        PopupMenu* p4 = new PopupMenu("기타");

 

        p1->Add( p2 );

        p1->Add( p3 );

        p1->Add( p4 );

 

        p2->Add( new MenuItem("신규고객등록", 1) );

        p2->Add( new MenuItem("고객삭제", 2) );

        p2->Add( new MenuItem("기타", 2) );

 

        p3->Add( new MenuItem("신규Tape등록", 1) );

        p3->Add( new MenuItem("Tape삭제", 2) );

        p3->Add( new MenuItem("기타", 2) );

 

        p1->Command();

}

Tag |

8.7(화) C++ 디자인패턴 - Decorator

from Study/C++ 2007/08/08 20:30 view 21255

바닐라 : 1000

딸기   : 1500

초코   : 2000

 

아몬드 : 300

땅콩   : 200

키위   : 500

 

OCP 기능 확장에는 열려 있고 코드 변경에는 닫혀 있도록 해야 한다.

 

Decorator

 

객체(포장대상) - Item(동일 부모) – 포장지( Item& ) 재귀관점!!

cost() : item.cost() + 자신 // 자신을 꾸며서 리턴하므로 Decorator

 

연결. 데코레이터. 감싸주는것. 감싸서 기능을 합쳐준다.!!!!

아이템을 바꾸는건 전략 패턴..

아이템에 힘을 더해주는건 데코레이터 패턴

비행기를 생산하는건 팩토리 패턴..!!



#include <iostream>

using namespace std;

 

// Decorator 패턴:  객체와 포장을 동일하게 다룬다.

 

// Subject와 포장(Decorator)가 가져야 하는 공통의 인터페이스

struct Item

{

        virtual int cost() = 0;

};

 

// Ice Cream 객체.. 대상(Subject).

class Valina: public Item

{

public:

        virtual int cost() { return 1000; }

};

 

class Strawberry: public Item

{

public:

        virtual int cost() { return 1500; }

};

 

class Choko: public Item

{

public:

        virtual int cost() { return 2000; }

};

//----------------------------------------------------

// Decorator 객체들. 내부적으로 Subject의 참조를 가지고 있다.

 

class Almond : public Item

{

        Item& item;

public:

        Almond( Item& i ) : item(i) { }

 

        virtual int cost()

        {

               return item.cost() + 300;

        }

};

 

class Peanut : public Item

{

        Item& item;

public:

        Peanut( Item& i ) : item(i) { }

 

        virtual int cost()

        {

               return item.cost() + 200;

        }

};

 

class Kiwi : public Item

{

        Item& item;

public:

        Kiwi( Item& i ) : item(i) { }

 

        virtual int cost()

        {

               return item.cost() + 500;

        }

};

 

void main()

{

        Valina ice;

 

        Almond a( ice );

        cout << a.cost() << endl;

 

        Peanut p( a );

        cout << p.cost() << endl;

}

 
////////////////////////////////////////////////////

// Decorator의 예 ..
// MFC에서

void main()

{

        int n = 10;

 

        CFile f( "a.txt", CFile::Create );

 

        f.WriteFile( &n );

 

        CArchive ar( &f, CArchive::store );

        ar << n; // ok.

 

        CSocketFile sf;        // 네트워크

        CArchive( &sf, CArchive::store );

        ar2 >> n;

}

Tag | ,

// OCP에 위반된다. 소스변경을 해야 한다.

// Template Method 라고 불리는 디자인설계

// 1. 전체 알고리즘을 부모에게 둔다.(public, 절대가상이아니다.)

// 2. 알고리즘이 사용하는 세부구현은 가상함수로 만들어서 자식이 구현한다.(protected로구현)

 

class IceCream

{

        bool hasPeanut;

        bool hasAlmond;

        bool hasKiwi;

public:

        IceCream( bool b1, bool b2, bool b3 )

               : hasPeanut(b1), hasAlmond(b2), hasKiwi(b3) {}

 

        int cost()

        {

               int s = IceCost();

 

               if( hasPeanut ) s += 200;

               if( hasAlmond ) s += 300;

               if( hasKiwi )   s += 500;

 

               return s;

        }

 

protected:

        // NVI 가상함수를public으로만들지말자.

        virtual int IceCost() = 0;

};

 

class Vanila : public IceCream

{

public:

        Vanila( bool b1, bool b2, bool b3 ) : IceCream( b1, b2, b3 ) {}

        virtual int IceCost() { return 1000; }

};

 

class Strawberry : public IceCream

{

public:

        Strawberry( bool b1, bool b2, bool b3 ) : IceCream( b1, b2, b3 ) {}

        virtual int IceCost() { return 1500; }

};

 

class Choko : public IceCream

{

public:

        Choko( bool b1, bool b2, bool b3 ) : IceCream( b1, b2, b3 ) {}

        virtual int IceCost() { return 2000; }

};

 

void main()

{

        Choko c1( 1, 1, 0 );

 

        cout << c1.cost() << endl;

}

Tag | ,

#include <iostream>

#include <string>

using namespace std;

 

// 모든 반복자가 가져야 하는 인터페이스를 설계한다. - 실제 C#에는 아래의 interface가 있다.

 

// C# 1.0 에서는 Object 최상위클래스로 받아서 타입캐스팅을 했지만..

// C# 2.0 에서는 Generic의 도입으로 반복자 인터페이스가 편리해졌다.

template<typename T> struct IEnumerator

{

        virtual bool MoveNext() = 0;

        virtual T GetObject() = 0;

        virtual void Reset() = 0;

};

//-------------------------------------------------------

// 또한 반복자를 가질 수 있는 모든 컨테이너는 아래의 인터페이스를 제공해야 한다.

template<typename T> struct IEnumerable

{

        virtual IEnumerator<T>* GetEnumerator() = 0;

};

 

//-------------------------------------------------------

// 열거가능한(반복자를가진) 클래스는 반드시 IEnumerable에서 파생되어야 한다.

template<typename T> class slist : public IEnumerable<T>

{

        struct Node

        {

               T     data;

               Node* next;

 

               Node( T a, Node* n ) : data(a), next(n) {}

        };

 

        Node* head;

public:

        slist() : head(0) {}

 

        void push_back( T a ) { head = new Node( a, head ); }

 

        // slist에서 값을 얻기 위한 반복자

        class SlistEnumerator : public IEnumerator<T>

        {

               Node* current;

               Node* head;

        public:

               SlistEnumerator( Node* init = 0 ) 
               : head(init), current(init) {}

 

               bool MoveNext()

               {

                       current = current->next;

                       return current != 0;

               }

               int  GetObject() { return current->data; }

               void Reset() { current = head; }

        };

 

        //--------------------------------------------------

        // 반복자를 리턴하는 함수를 만든다.

        IEnumerator<T>* GetEnumerator()

        {

               return new SlistEnumerator( head );

        }

};

 

//------------------------------------------------------

// 주어진 반복자를 사용해서 모든 요소의 합을 구한다.

template<typename T> void Sum( IEnumerator<T>* p )

{

        T s = T();

 

        p->Reset();

 

        do

        {

               s += p->GetObject();

        } while ( p->MoveNext() );

 

        cout << s << endl;

}

// 주어진 컨테이너의 모든 요소의 합을 구한다.

template<typename T> void Sum2( IEnumerable<T>& c )

{

        IEnumerator<T>* p = c.GetEnumerator();

        Sum( p );

}

 

int main()

{

        slist<int> s;

 

        s.push_back( 10 );

        s.push_back( 20 );

        s.push_back( 30 );

 

        //IEnumerator<int>* p = s.GetEnumerator();

        //Sum( p );

 

        Sum2( s );

 

        return 0;

}

 

 

Tag |

8.6(월) C++ 디자인패턴 - Factory

from Study/C++ 2007/08/08 20:11 view 20396

#include <iostream>

using namespace std;

 

// factory : 객체 생성을 클래스화 해라.

 

// 도형 편집기를 만들고 싶다.

 

class Shape { };

class Rect : public Shape {};

class Circle : public Shape {};

 

// 이제 도형을 생성하는 공장의 인터페이스를 구현한다.

class IShapeFactory

{

public:

        virtual Shape* CreateShape( char c ) = 0;

};

 

class FactoryVer1 : public IShapeFactory

{

public:

        virtual Shape* CreateShape( char c )

        {

               switch( c )

               {

               case 'C':

                       return new Circle;

               case 'R':

                       return new Rect;

               }

        }

};

 

class FactoryVer2 : public IShapeFactory

{

public:

        virtual Shape* CreateShape( char c )

        {

               switch( c )

               {

               case 'C':

                       return new Circle;

               case 'R':

                       return new Rect;

               case 'T':

                       return new Triangle;   // 확장의 유용성!!

               }

        }

};

 

class Canvas

{

        vector<Shape*> shapes;

        IShapeFactory* factory;

public:

 

        void Save()

        {

        }

        void Load()

        {

               // 어떤 객체인지 표시를 읽어내고, 해당 data를 읽은 후에

               char c = Read();

               char data = Read();

 

               shapes.push_back( factory->CreateShape( c ) ); // 위임한다.

 

               //switch( c )

               //{

               //case 'R':

               //      shapes.push_back( new Rect(data) );

               //      break;

 

               //case 'C':

               //      shapes.push_back( new Circle(data) );

               //      break;

               //}

 

        }

 

        void KeyDown( char c )

        {

               shape.push_back( factory->CreateShape( c ) ); // 위임한다.

 

               //switch( c )

               //{

               //case 'R':

               //      shapes.push_back( new Rect );

               //      break;

               //case 'C':

               //      shapes.push_back( new Circle );

               //      break;

               //}

        }

};

 

Tag | ,