2012-11-29 62 views
0

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

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

+4

你想查找[UML](http://en.wikipedia.org/wiki/Unified_Modeling_Language)。 –

回答

3

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

0

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

这UML与笔记和驼峰看起来像Java,
但这里是从你的图做一些C++模式:

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

在看代码之前,让我说我讨厌骆驼大小写,我宁愿鼓励你像C++库一样执行underscore_notation,就像STL和Boost那样做。因此我已经改变了每个类以强调符号。 实施的一部分。因此可以这个样子:

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”代表“接口”。