所謂訪問者模式,就是不同服務提供者對同一種服務提供的服務內容不同。
Typedef std::vector<Ivisitable> VisitbleArray;
Typedef std::vector<IVisitor> VisitorArray;
Interface IVisitable
{
void AcceptSum(IVisitor visitor);
void AcceptAvg(IVisitor visitor);
void CalcSum( IVisitor visitor) ;
void CalcAvg(IVisitor visitor);
void Attach( Ivisitor v);
void Detach ( Ivisitor v);
}
Typedef std::vector<Ivisitable> VisitbleArray;
Interface IVisitor
{
void GetSum ( IVisitable v);
void GetAvg(IVisitable v);
void VisitSumCollection(VisitbleArray collection);
void VisitAvgCollection(VisitbleArray collection);
}
Class CVisitor1: public IVisitor
{
void GetSum ( IVisitable v)
{
Printf(“ vistor1 invoke: \n”);
v. AcceptSum (this);
}
void GetAvg(IVisitable v)
{
Printf(“ vistor1 invoke: \n”);
v.AcceptAvg(this);
}
//在本方法中,我們實現了對Collection的元素的成功訪問
void VisitSumCollection(VisitbleArray collection) {
VisitbleArray::Iterator
it = collection.begin();
while (it !=
collection.end())
{
it->AcceptSum(this);
It++;
}
}
void VisitAvgCollection(VisitbleArray collection) {
VisitbleArray::Iterator
it = collection.begin();
while (it !=
collection.end())
{
it->AcceptAvg(this);
It++;
}
}
Class CVisitor2: public IVisitor
{
void GetSum ( IVisitable v)
{
Printf(“ vistor2 invoke: \n”);
v. AcceptSum (this);
}
void GetAvg(IVisitable v)
{
Printf(“ vistor2 invoke: \n”);
v.AcceptAvg(this);
}
//在本方法中,我們實現了對Collection的元素的成功訪問
void VisitSumCollection(VisitbleArray collection) {
VisitbleArray::Iterator
it = collection.begin();
while (it !=
collection.end())
{
it->AcceptSum(this);
It++;
}
}
void VisitAvgCollection(VisitbleArray collection) {
VisitbleArray::Iterator
it = collection.begin();
while (it !=
collection.end())
{
it->AcceptAvg(this);
It++;
}
}
Class CProduct1 : public IVisitable
{
void AcceptSum(IVisitor visitor)
{
visitor-> GetSum(this);
}
void AcceptAvg(IVisitor visitor)
{
Visitor->GetAvg(this);
}
void CalcSum( IVisitor visitor)
{
Float sum =0.0;
for(std::vector<float>::iterator it = m_Vec.begin(); m_vec.end();it++)
Sum += *it;
Printf(“ product1 calc sum is =%f\n”,sum);
}
void CalcAvg( IVisitor visitor)
{
Float sum =0.0,avg=0.0;
for(std::vector<float>::iterator it = m_Vec.begin(); m_vec.end();it++)
Sum += *it;
avg=sum/ m_Vec.size();
Printf(“ product1 calc avg is =%f\n”,avg);
}
private:
std::vector<float> m_Vec;
}
Class CProduct2 : public IVisitable
{
void AcceptSum(IVisitor visitor)
{
visitor-> GetSum(this);
}
void AcceptAvg(IVisitor visitor)
{
Visitor->GetAvg(this);
}
void CalcSum( IVisitor visitor)
{
Float sum =0.0;
for(std::vector<float>::iterator it = m_Vec.begin(); m_vec.end();it++)
Sum += *it;
Printf(“ product2 calc sum is =%f\n”,sum);
}
void CalcAvg( IVisitor visitor)
{
Float sum =0.0,avg=0.0;
for(std::vector<float>::iterator it = m_Vec.begin(); m_vec.end();it++)
Sum += *it;
avg=sum/ m_Vec.size();
Printf(“ product2 calc avg is =%f\n”,avg);
}
private:
std::vector<float> m_Vec;
}
所謂觀察者式,就是不同種觀察者希望提供一種服務。