修改後的specification模式c++實現,去掉了介面名的I字首
//specification.h
#pragma once
template<class T>
class Specification
{
public:
virtual bool IsSatisfiedBy(T candidate) = 0;
virtual Specification<T>* And(Specification<T>* other) = 0;
virtual Specification<T>* Or(Specification<T>* other) = 0;
virtual Specification<T>* Not() = 0;
};
template<class T>
class CompositeSpecification : public Specification<T>
{
public:
virtual bool IsSatisfiedBy(int candidate) = 0;
virtual Specification<T>* And(Specification<T>* other);
virtual Specification<T>* Or(Specification<T>* other);
virtual Specification<T>* Not();
};
template<class T>
class AndSpecification : public CompositeSpecification<T>
{
public:
AndSpecification(Specification<T>* x, Specification<T>* y)
{
m_one = x;
m_other = y;
}
virtual bool IsSatisfiedBy(int candidate)
{
return m_one->IsSatisfiedBy(candidate) && m_other->IsSatisfiedBy(candidate);
}
private:
Specification<T>* m_one;
Specification<T>* m_other;
};
template<class T>
class OrSpecification : public CompositeSpecification<T>
{
public:
OrSpecification(Specification<T>* x, Specification<T>* y)
{
m_one = x;
m_other = y;
}
virtual bool IsSatisfiedBy(int candidate)
{
return m_one->IsSatisfiedBy(candidate) || m_other->IsSatisfiedBy(candidate);
}
private:
Specification<T>* m_one;
Specification<T>* m_other;
};
template<class T>
class NotSpecification : public CompositeSpecification<T>
{
public:
NotSpecification(Specification<T>* x)
{
m_wrapped = x;
}
virtual bool IsSatisfiedBy(int candidate)
{
return !m_wrapped->IsSatisfiedBy(candidate);
}
private:
Specification<T> *m_wrapped;
};
//CompositeSpecification
template<class T>
Specification<T>* CompositeSpecification<T>::And(Specification<T>* other)
{
return new AndSpecification<T>(this, other);
}
template<class T>
Specification<T>* CompositeSpecification<T>::Or(Specification<T>* other)
{
return new OrSpecification<T>(this, other);
}
template<class T>
Specification<T>* CompositeSpecification<T>::Not()
{
return new NotSpecification<T>(this);
}
//test.cpp
#include "specification.h"
#include <vector>
#include <algorithm>
using namespace std;
class OddSpecification : public CompositeSpecification<int>
{
public:
virtual bool IsSatisfiedBy(int candidate)
{
return candidate % 2 != 0;
}
};
class PositiveSpecification : public CompositeSpecification<int>
{
public:
virtual bool IsSatisfiedBy(int candidate)
{
return candidate > 0;
}
};
int main(int argc, char* argv[])
{
vector<int> vint;
for (int i = -5; i < 10; i++)
vint.push_back(i);
Specification<int> *oddSpec = new OddSpecification();
Specification<int> *positiveSpec = new PositiveSpecification();
Specification<int> *oddAndPositiveSpec = oddSpec->And(positiveSpec);
for (vector<int>::iterator it = vint.begin(); it != vint.end(); ++it)
{
if (oddAndPositiveSpec->IsSatisfiedBy(*it))
//if (oddSpec->IsSatisfiedBy(*it))
printf("%d\n", *it);
}
delete oddSpec;
delete positiveSpec;
delete oddAndPositiveSpec;
system("PAUSE");
return 0;
}
//vs2013測試通過