也许您正在寻找一种策略模式?假设 AF 编码behavior,您可以“混合”不同的行为或将它们作为策略提供:
注意:下面,静态/非静态成员函数之间的分离有点随意(mixin可以很好地包含静态成员)。
混合
#include <iostream>
struct NormalPartABehaviour {
void A() { std::cout << "Normal A" << std::endl; }
void B() { std::cout << "Normal B" << std::endl; }
void C() { std::cout << "Normal C" << std::endl; }
};
struct SpecialPartABehaviour {
void A() { std::cout << "Special A" << std::endl; }
void B() { std::cout << "Special B" << std::endl; }
void C() { std::cout << "Special C" << std::endl; }
};
struct NormalPartBBehaviour {
void D() { std::cout << "Normal D" << std::endl; }
void E() { std::cout << "Normal E" << std::endl; }
void F() { std::cout << "Normal F" << std::endl; }
};
template <typename PartAMixin, typename PartBMixin>
struct GlobalContext : public PartAMixin, public PartBMixin
{
};
///// test method:
template <class Context>
void test(Context globalcontext)
{
globalcontext.A();
globalcontext.B();
globalcontext.C();
globalcontext.D();
globalcontext.E();
globalcontext.F();
}
int main()
{
GlobalContext<NormalPartABehaviour, NormalPartBBehaviour> ctx1;
GlobalContext<SpecialPartABehaviour, NormalPartBBehaviour> ctx2;
std::cout << "testing ctx1: \n";
test(ctx1);
std::cout << "testing ctx2: \n";
test(ctx2);
}
输出http://liveworkspace.org/code/b6b5cfffba11df68bc70c432b030b1d5
testing ctx1:
Normal A
Normal B
Normal C
Normal D
Normal E
Normal F
testing ctx2:
Special A
Special B
Special C
Normal D
Normal E
Normal F
战略
#include <iostream>
struct NormalPartABehaviour {
static void A() { std::cout << "Normal A" << std::endl; }
static void B() { std::cout << "Normal B" << std::endl; }
static void C() { std::cout << "Normal C" << std::endl; }
};
struct SpecialPartABehaviour {
static void A() { std::cout << "Special A" << std::endl; }
static void B() { std::cout << "Special B" << std::endl; }
static void C() { std::cout << "Special C" << std::endl; }
};
struct NormalPartBBehaviour {
static void D() { std::cout << "Normal D" << std::endl; }
static void E() { std::cout << "Normal E" << std::endl; }
static void F() { std::cout << "Normal F" << std::endl; }
};
template <typename PartAMixin, typename PartBMixin>
struct GlobalContext
{
static void A() { PartAMixin::A(); }
static void B() { PartAMixin::B(); }
static void C() { PartAMixin::C(); }
static void D() { PartBMixin::D(); }
static void E() { PartBMixin::E(); }
static void F() { PartBMixin::F(); }
};
///// test method:
template <class Context>
void test()
{
Context::A();
Context::B();
Context::C();
Context::D();
Context::E();
Context::F();
}
int main()
{
typedef GlobalContext<NormalPartABehaviour, NormalPartBBehaviour> ctx1;
typedef GlobalContext<SpecialPartABehaviour, NormalPartBBehaviour> ctx2;
std::cout << "testing ctx1: \n";
test<ctx1>();
std::cout << "testing ctx2: \n";
test<ctx2>();
}
输出http://liveworkspace.org/code/8bca96d0e9784026c6357a30110bc5fd
testing ctx1:
Normal A
Normal B
Normal C
Normal D
Normal E
Normal F
testing ctx2:
Special A
Special B
Special C
Normal D
Normal E
Normal F