Homedepot (HD) hires two furniture factories: ChineseFurnitureFactory and SpanishFurnitureFactory to make doors and floors.
class Wood
{
public:
int a;
Wood(int a=3)
{
this->a = a;
}
friend ostream& operator<<(ostream& out, Wood a)
{
out << a.a << " " ;
return out;
}
Wood& operator*(int n)
{
a *= n;
return *this;
}
};
template <typename T>
class FurnitureFactory
{
public:
typedef T Door;
typedef T Floor;
virtual void cutWood(T a) = 0;
virtual Door makeDoor() = 0;
virtual Floor makeFloor() =0;
virtual ~FurnitureFactory(){}
};
template <typename T>
class ChineseFurnitureFactory : public FurnitureFactory<T>
{
T a;
public:
void cutWood(T a)
{
cout << a.a << " is cut into 2 x 4 x 8 in wood factory" << endl;
this->a = a * 100;
}
typename FurnitureFactory<T>::Door makeDoor()
{
typename::FurnitureFactory<T>::Door result = a ;
return result;
}
typename::FurnitureFactory<T>::Floor makeFloor()
{
typename::FurnitureFactory<T>::Floor result = a;
return result;
}
};
template <typename T>
class SpanishFurnitureFactory : public FurnitureFactory<T>
{
T a;
public:
void cutWood(T a)
{
cout << a.a << " is cut into 1 x 2 x 4 in wood factory" << endl;
this->a = a;
}
typename::FurnitureFactory<T>::Door makeDoor()
{
typename::FurnitureFactory<T>::Door result = a ;
return result;
}
typename::FurnitureFactory<T>::Floor makeFloor()
{
typename::FurnitureFactory<T>::Floor result = a;
return result;
}
};
template < typename T = Wood,
int N = 3,
typename O = ChineseFurnitureFactory<T> >
class HD
{
O ops;
T a;
static const int b = N;
public:
void sellDoor(T a)
{
ops.cutWood(a);
typename O::Door d = ops.makeDoor();
cout << N << " doors made of " << d << " are sold " << endl;
}
void sellFloor(T a)
{
ops.cutWood(a);
typename O::Floor d = ops.makeFloor();
cout << N << " Floors made of " << d << " are sold " << endl;
}
Yes, thanks for the link. In the link, inheritance is used between the execution class(HelloWorld) and policy classes, which I didn't do in my example. In my example, ChineseFurnitureFactory and SpanishFurnitureFactory
are the policy classes. Execution class HD (Homedepot) can hire two different factories to make furniture for it using a material (template parameter T), for example, class Wood. When HD calls sellDoor() / sellFloor(), it will sell
different styles of door/floor depending on which factory ( policy class ) it uses.
By the way, I intentionally added some default values in the declaration of class HD as part of practicing template programming. I will be focusing on template programming recently, so it's likely I will post similar threads in the near future.
template < typename T = Wood,
int N = 3,
typename O = ChineseFurnitureFactory<T> >
class HD