开发者

OO design, table design

Design table with wood or steel meterial. I have following designed, which is better and why? Or any better suggestion design?

design 1 :

class Meterial{
public:
  void virtual info()=0;
};

class Wood:public Meterial{
public:
  void info();
};

void Wood::info(){
  cout<<"wood"<< " ";
}

class Steel:public Meterial{
public:
  void info();
};

void Steel::info(){
  cout<<"steel"<< " ";
}




class Furniture{
  void virtual info()=0;
};

class Table:public Furniture{
private:
  Meterial * _meterial;
public:
  Table(Meterial * m);
  void info();
};

Table::Table(Meterial * m){
  _meterial= m;
}


void Table::info(){
  _meterial->info();
  cout<< " table " << endl;
}

int main(){
  Table * wood_table=new Table(new Wood());
  Table * steel_table=new Table(new Steel());
  wood_table->info();
  steel_table->info();
}

design 2:

class Meterial{
public:
  virtual void info()=0;
};

class Wood:public Meterial{
public:
  void info();
};

void Wood::info(){
  cout<<" wood " <<开发者_如何转开发 " ";
}

class Steel:public Meterial{
public:
  void info();
};

void Steel::info(){
  cout<<" Steel " << " ";
}



class Furniture{
public:
  virtual void info()=0;
};

class Table:public Furniture{
public:
  void info();
};

void Table::info(){
  cout<<" table "<< endl;
}

class WoodTable:public Wood,public Table{
public:
  void info();
};

void WoodTable::info(){
  Wood::info();
  Table::info();
}


class SteelTable:public Steel,public Table{
public:
  void info();
};

void SteelTable::info(){
  Steel::info();
  Table::info();
}



int main(){
  WoodTable *woodTable = new WoodTable();
  SteelTable *steelTable = new SteelTable();

  woodTable->info();
  steelTable->info();
}

thanks!


You should only use inheritance when you have a very specific reason to, or when all other options are not better nor worse. Never inherit for reuse.

Does material have any behaviour that can change dynamically? Can the table's material change at runtime? If the answer is yes to either of these then you'll likely need runtime polymorphism and inheritance. Your first design is then a good step in the right direction. Your second design, however, is risky and brings little to the table (and pardon the pun). Multiple inheritance? Why? You should have a very specific, solid reason to use multiple inheritance.

Another design alternative is to use compile-time polymorphism.

struct wood { };
struct steel { };

template<class M>
struct table { };

// ...
table<wood> wood_table;


Think of the difference between "is a" and "has a". A table has a material property, a table itself isn't a material. I would go with the first one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜