[关闭]
@913094331 2019-08-02T03:46:11.000000Z 字数 2103 阅读 537

Factory Pattern Sample

C++ DesignPattern OOP


Source Code

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Shape{
  5. public:
  6. virtual void Draw() {};
  7. };
  8. class Circle : public Shape{
  9. void Draw(){ cout<<"Draw a circle"<<endl; }
  10. };
  11. class Square : public Shape{
  12. void Draw(){ cout<<"Draw a square"<<endl; }
  13. };
  14. class Rectangle : public Shape{
  15. void Draw(){ cout<<"Draw a rectangle"<<endl; }
  16. };
  17. class Triangle : public Shape{
  18. void Draw(){ cout<<"Draw a triangle"<<endl; }
  19. };
  20. class Casual : public Shape{
  21. void Draw(){ cout<<"Draw casually"<<endl; }
  22. };
  23. class ShapeFactory{
  24. public:
  25. static Shape* Relshape(string type) {
  26. if(!type.compare("CIRCLE")) {
  27. return new Circle();
  28. } else if(!type.compare("SQUARE")) {
  29. return new Square();
  30. } else if(!type.compare("RECTANGLE")) {
  31. return new Rectangle();
  32. } else if(!type.compare("TRIANGLE")) {
  33. return new Triangle();
  34. } else {
  35. return new Casual();
  36. }
  37. }
  38. };
  39. class FactoryPattern{
  40. public:
  41. FactoryPattern(){
  42. cout<<"************MENU*************"<<endl;
  43. cout<<"*** 1.CirCle ***"<<endl;
  44. cout<<"*** 2.Square ***"<<endl;
  45. cout<<"*** 3.Rectangle ***"<<endl;
  46. cout<<"*** 4.Triangle ***"<<endl;
  47. cout<<"*** 5.Casually ***"<<endl;
  48. cout<<"*****************************"<<endl;
  49. cout<<"FactoryPattern------What do you want to draw?"<<endl;
  50. cout<<"Answer----- ";
  51. cin>>tag;
  52. switch(tag)
  53. {
  54. case 1:shape= ShapeFactory::Relshape("CIRCLE"); break;
  55. case 2:shape= ShapeFactory::Relshape("SQUARE"); break;
  56. case 3:shape= ShapeFactory::Relshape("RECTANGLE"); break;
  57. case 4:shape= ShapeFactory::Relshape("TRIANGLE"); break;
  58. default:shape= ShapeFactory::Relshape(""); break;
  59. }
  60. shape->Draw();
  61. }
  62. ~FactoryPattern(){}
  63. private:
  64. int tag;
  65. Shape* shape;
  66. };
  67. int main()
  68. {
  69. FactoryPattern factory;
  70. return 0;
  71. }

Debug

  1. error : expected '}' at end of input
    reason : lose matching '}'
    solution : check all {} one by one
  2. error : could not convert '……' from 'Circle*' to 'Shape'
    reason : type matching failed
    solution : check the return-value and return-type of the function and assignment variables' type
  3. error : "……" is private within this context
    reason : lose the tag "public:" in class
  4. error : undefined reference to `vtable for Shape'
    reason : undefined reference stands failure in process of link, 'vtable' is created by virtual interface class, this error stands the definition has not been implemented
    solution : "virtual void Draw();" -> "virtual void Draw() {};"

tips:
new class should be defined with () , e.g. new Cirle()

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注