大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks

定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
本模式使得算法可独立于使用它的客户而变化.


客户端通过算法的父类指针调用虚函数方法,具体的子类算法对象在运行时传给客户端,这样可以保证客户端代码的不变性。
 

#include <iostream>

using namespace std;


//Abstract Interface
class Algorithm
{
public:
    
virtual void Process() = 0;
}
;


//Implementation
class AlgorithmA:public Algorithm
{
public:
    
void Process() 
    
{
        cout
<<"Algorithm A"<<endl;
    }

}
;

class AlgorithmB:public Algorithm
{
public:
    
void Process() 
    
{
        cout
<<"Algorithm B"<<endl;
    }

}
;


//Client
class Client
{
private:
    Algorithm 
*m_pAl;
public:
    Client()
    
{
        m_pAl 
= NULL;
    }


    
~Client()
    
{
        
if(NULL != m_pAl)
        
{
            delete m_pAl;
            m_pAl 
= NULL;
        }

    }


    
void Method(Algorithm *pAl)
    
{
        
if(NULL != m_pAl)
        
{
            delete m_pAl;
            m_pAl 
= NULL;
        }

        m_pAl 
= pAl;
        m_pAl
->Process();
    }

}
;


int main()
{
    Client t;

    t.Method(
new AlgorithmA());
    t.Method(
new AlgorithmB());

    
return 0;
}


posted on 2009-05-27 11:50 大胖 阅读(99) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理