0

我刚从初学者开始学习更多关于 C++ 设计模式的知识。我终于开始阅读http://sourcemaking.com/design_patterns网站。但是在遇到http://sourcemaking.com/files/sm/images/patterns/Abstract_Factory.gif图像后,我无法将图像映射到现实中的实际类(及其接口)构造。

矩形、箭头、虚线是什么以及我们如何将其转换为实际的代码实现?

4

3 回答 3

3

这些图是用 UML统一建模语言绘制的。您应该真正熟悉它们,因为为了研究设计模式,您并不需要实际的代码。是的,好吧,最终你必须用你想要的语言来实现设计模式,但是对模式的理解必须比代码更高。

于 2012-11-29T15:04:17.380 回答
1

这是 UML http://en.wikipedia.org/wiki/Unified_Modeling_Language描述软件设计的一种语言。这种和设计模式独立于任何编程语言

于 2012-11-29T15:03:54.070 回答
0

回答:“我们如何将其转换为实际的代码实现?”

这个带有注释和 CamelCase 的 UML 看起来像 Java,
但下面是图中的一些 C++ 模式:

  • 箭头通常表示指针或 shared_ptr-s,
  • 白头箭头表示公共继承,
  • <<interface>>在 C++ 中表示抽象类,在 Java 中表示接口,
  • 带有虚线箭头的白色东西是笔记。在这种情况下,它们会为您提供实现细节,您也可以按字面输入它们。

在查看代码之前,让我说我讨厌驼峰式大小写,我宁愿鼓励你做 underscore_notation,因为像 STL 和 Boost 这样的 C++ 库就是这样做的。因此,我将每个班级都更改为下划线符号。 因此,部分实现可能如下所示:

class Abstract_platform {
public:
  virtual ~Abstract_platform()=0; // this UML does not specify any functions but we make this class abstract.
};
class Platform_one : public Abstract_platform {

};
class Platform_two : public Abstract_platform {
public:
  /// you should implement this make function with shared_ptr, OR NO POINTERS AT ALL but I go according to the notes
  Product_one_platform_two*  make_product_one();
  Product_two_platform_two*  make_product_two();
  // I provide you with a better_make. It is better than the former make functions
  // due to RVO (Return value optimization see wikipedia)
  // so this is again a hint that this UML was originally for Java.
  Product_one_platform_two better_make_product_one();
};

class Class1 {
private:
  Abstract_platform* platform; // OR shared_ptr<Abstract_platform>, OR Abstract_platform&
  Abstract_product_two* product_two;
};

/// **Implementation file**
Product_one_platform_two*  Platform_two::make_product_one() 
{
  return new Product_one_platform_two(); 
}
Product_two_platform_two*  Platform_two::make_product_two() 
{
  return new Product_two_platform_two(); 
}     
Product_one_platform_two Platform_two::better_make_product_one() 
{
  return Product_one_platform_two(); 
}

另请注意,Abstract_platform人们更喜欢IPlatform匈牙利符号,其中“I”代表“接口”。

于 2012-11-29T15:25:41.480 回答