标签:
所谓访问者模式,就是不同服务提供者对同一种服务提供的服务内容不同。
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;
}
所谓观察者式,就是不同种观察者希望提供一种服务。
标签:
原文地址:http://www.cnblogs.com/skyofbitbit/p/4231692.html