I came across the following question on a website for interviews:
Here are 3 products: table, chair and bench. Product can be of material: wood, metal, and plastic. Design class structures for this.
My first thought was to have an abstract class Product with a protected Material class member as shown below. My actual question is after the code block below
#include <stdio.h>
#include <string>
using namespace std;
class Type {
public:
// Commented out virtual below. Was a typo !
/*virtual*/void SetType(string s) {
m_typeName = s;
}
virtual void PrintType() {
printf("Type = %s\n",m_typeName.c_str());
}
virtual ~Type()=0;
Type& operator=(const Type& rhs) {
if ( &rhs != this ) {
m_typeName = rhs.m_typeName;
}
return *this;
}
private:
string m_typeName;
};
Type::~Type() {}
class Wood: public Type {
};
class Plastic: public Type {
};
class Product {
public:
Product():m_type(NULL) {
}
virtual void SetType(Type* t){
m_type = t;
}
virtual void PrintInfo() {
printf("I am %s product\n",m_productName.c_str());
m_type->PrintType();
}
virtual ~Product()=0;
protected:
string m_productName;
Type* m_type;
};
Product::~Product() {}
class Table: public Product {
public:
Table() {
m_productName = "table";
}
};
class Chair: public Product {
public:
Chair() {
m_productName = "chair";
}
};
int main()
{
Plastic *p = new Plastic();
p->SetType("plastic");
Table *t = new Table();
t->SetType(p);
t->PrintInfo();
delete t;
delete p;
return 0;
}
However, I have a feeling it could be designed better.
In general, if your compositions (Product in the example) contain compositions (Material in the example), what is a good design pattern?