Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
d994d72
Initial commit
Sep 11, 2019
0388f60
format output
Sep 11, 2019
bf58a87
Update README.md
ederfduran Sep 16, 2019
76bc6e4
Update README.md
ederfduran Sep 16, 2019
a18acef
Update README.md
ederfduran Sep 16, 2019
7cfebe1
google std changes
Sep 16, 2019
b95813d
Merge branch 'master' of https://github.com/ederfduran/design-pattern…
Sep 16, 2019
7489c0b
Initial commit Factory Method
Sep 16, 2019
087995d
Builder initial commit
Sep 18, 2019
5ece861
Protorypes initial commit
Sep 20, 2019
8f6635a
fix indentation and move fire method
Oct 2, 2019
399efc8
Singleton pattern
Oct 2, 2019
b605458
out
Oct 2, 2019
465bf1a
name syntax
Oct 2, 2019
93435d9
Prototype names change
Oct 3, 2019
d0ce78d
Thread - NonThread Singleton
Oct 3, 2019
8fa92c6
Adapter Example
Oct 4, 2019
a5ac74a
delete atomic
Oct 4, 2019
7004f58
Bridge Pattern
Oct 7, 2019
655e764
delete unused files and add prototypes pattern
Oct 9, 2019
d47e989
Singleton Multithread fail sample added
Oct 10, 2019
2ad64be
Complete Adapter with multiple Inheritance example
Oct 10, 2019
b6e966d
Composite Example
Oct 10, 2019
e64c597
facade and decorator Pattern
Oct 11, 2019
a8ae091
Flyweight pattern
Oct 16, 2019
bb4323a
add Proxy
Oct 16, 2019
c4c3ebf
Chain of responsability pattern
Oct 17, 2019
fc41083
Command Pattern
Oct 17, 2019
13e8172
Iterator design pattern
Oct 19, 2019
80889d3
Mediator design pattern
Oct 19, 2019
ef3dcd7
Memento design pattern
Oct 19, 2019
3534216
Observer design pattern
Oct 25, 2019
63cb7d4
State design pattern
Oct 26, 2019
f5b612d
add Output
Oct 26, 2019
83de41d
Strategy Pattern
Oct 26, 2019
9aafd25
Template Method Design Pattern
Oct 27, 2019
e6681ce
Visitor design pattern
Oct 28, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,50 @@ It contains C++ examples for all classic GoF design patterns. Each pattern inclu

## Requirements

TODO

The examples were written as cross platform console application using c++11. It means that you should be able to compile and execute those examples with any recent compiler.

we recommend working with Visual Studio Code because it is a lightweight and cross-platform tool .It is a very complete IDE and is available for free (https://code.visualstudio.com/). You may need to install c++ extension and the compiler you prefer (The extension is still in preview and its focus is code editing, navigation, and debugging support for C and C++). For more information on how to use VSCode with c++ refer to: https://code.visualstudio.com/docs/languages/cpp .

For code execution in VSCode you will need to set up your task first. An example using g++ :

```sh
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++ -g -std=c++11 Conceptual/main.cc -o main",
"group":{
"kind": "build",
"isDefault": true
},
"problemMatcher":"$gcc"
}
]
}
```
Then you just need to start the executable.In case you have some doubts here you have an useful [tutorial] using vscode.

## Contributor's Guide

TODO
I appreciate any help, whether it's a simple fix of a typo or a whole new example. Just make a fork, make your change and submit a pull request.

Here's a style guide which might help you to keep your changes consistent with the rest of the project's code:

1. All code should match the [Google style guide].
2. Aim to put all code within one .cc file. Yes, I realize that it's not how it supposed to be done in production. However, it helps people to understand examples better, since all code fits into one screen.
3. The comments doesn't follow the style guide for compatibility reasons withe other language examples.



## License

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.

<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/80x15.png" /></a>



[Google style guide]: <https://google.github.io/styleguide/cppguide.html#C++_Version>
[tutorial]: <https://www.youtube.com/watch?v=-erXR6k9TeE>
8 changes: 8 additions & 0 deletions src/AbstractFactory/Conceptual/Output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

Client: Testing client code with the first factory type:
The result of the product B1.
The result of the B1 collaborating with the (The result of the product A1.)

Client: Testing the same client code with the second factory type:
The result of the product B2.
The result of the B2 collaborating with the (The result of the product A2.)
247 changes: 247 additions & 0 deletions src/AbstractFactory/Conceptual/main.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
#include <iostream>
#include <string>

/**
* EN: Abstract Factory Design Pattern
*
* Intent: Lets you produce families of related objects without specifying their
* concrete classes.
*
* RU: Паттерн Абстрактная Фабрика
*
* Назначение: Предоставляет интерфейс для создания семейств связанных или
* зависимых объектов без привязки к их конкретным классам.
*/
/**
* EN: The Abstract Factory interface declares a set of methods that return
* different abstract products. These products are called a family and are
* related by a high-level theme or concept. Products of one family are usually
* able to collaborate among themselves. A family of products may have several
* variants, but the products of one variant are incompatible with products of
* another.
*
* RU: Интерфейс Абстрактной Фабрики объявляет набор методов, которые возвращают
* различные абстрактные продукты. Эти продукты называются семейством и связаны
* темой или концепцией высокого уровня. Продукты одного семейства обычно могут
* взаимодействовать между собой. Семейство продуктов может иметь несколько
* вариаций, но продукты одной вариации несовместимы с продуктами другой.
*/

class AbstractProductA;
class AbstractProductB;

class AbstractFactory
{
public:
virtual AbstractProductA* CreateProductA() const = 0;
virtual AbstractProductB* CreateProductB() const = 0;
};

/**
* EN: Each distinct product of a product family should have a base interface.
* All variants of the product must implement this interface.
*
* RU: Каждый отдельный продукт семейства продуктов должен иметь базовый
* интерфейс. Все вариации продукта должны реализовывать этот интерфейс.
*/

class AbstractProductA
{
/**
* EN: Define virtual destructor in case you need it.
*
* RU:
*/
public:
virtual ~AbstractProductA(){};
virtual std::string UsefulFunctionA() const = 0;
};


/**
* EN: Concrete Products are created by corresponding Concrete Factories.
*
* RU: Конкретные продукты создаются соответствующими Конкретными Фабриками.
*/

class ConcreteProductA1 : public AbstractProductA
{
public:
std::string UsefulFunctionA() const override
{
return "The result of the product A1.";
}
};

class ConcreteProductA2 : public AbstractProductA
{
std::string UsefulFunctionA() const override
{
return "The result of the product A2.";
}
};

/**
* EN: Here's the the base interface of another product. All products can
* interact with each other, but proper interaction is possible only between
* products of the same concrete variant.
*
* RU: Базовый интерфейс другого продукта. Все продукты могут взаимодействовать
* друг с другом, но правильное взаимодействие возможно только между продуктами
* одной и той же конкретной вариации.
*/

class AbstractProductB
{
/**
* EN: Product B is able to do its own thing...
*
* RU: Продукт B способен работать самостоятельно...
*/
public:
virtual ~AbstractProductB(){};

virtual std::string UsefulFunctionB() const = 0;
/**
* EN: ...but it also can collaborate with the ProductA.
*
* The Abstract Factory makes sure that all products it creates are of the
* same variant and thus, compatible.
*
* RU: ...а также взаимодействовать с Продуктами Б той же вариации.
*
* Абстрактная Фабрика гарантирует, что все продукты, которые она создает,
* имеют одинаковую вариацию и, следовательно, совместимы.
*/
virtual std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const = 0;
};

/**
* EN: Concrete Products are created by corresponding Concrete Factories.
*
* RU: Конкретные Продукты создаются соответствующими Конкретными Фабриками.
*/

class ConcreteProductB1: public AbstractProductB{
public:

std::string UsefulFunctionB() const override{
return "The result of the product B1.";
}
/**
* EN: The variant, Product B1, is only able to work correctly with the
* variant, Product A1. Nevertheless, it accepts any instance of
* AbstractProductA as an argument.
*
* RU: Продукт B1 может корректно работать только с Продуктом A1. Тем не
* менее, он принимает любой экземпляр Абстрактного Продукта А в качестве
* аргумента.
*/
std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const override{
const std::string result= collaborator.UsefulFunctionA();
return "The result of the B1 collaborating with ( "+ result+" )";
}
};

class ConcreteProductB2: public AbstractProductB{
public:
std::string UsefulFunctionB() const override{
return "The result of the product B2.";
}

/**
* EN: The variant, Product B2, is only able to work correctly with the
* variant, Product A2. Nevertheless, it accepts any instance of
* AbstractProductA as an argument.
*
* RU: Продукт B2 может корректно работать только с Продуктом A2. Тем не
* менее, он принимает любой экземпляр Абстрактного Продукта А в качестве
* аргумента.
*/
std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const override{
const std::string result= collaborator.UsefulFunctionA();
return "The result of the B2 collaborating with ( "+ result+" )";
}
};



/**
* EN: Concrete Factories produce a family of products that belong to a single
* variant. The factory guarantees that resulting products are compatible. Note
* that signatures of the Concrete Factory's methods return an abstract product,
* while inside the method a concrete product is instantiated.
*
* RU: Конкретная Фабрика производит семейство продуктов одной вариации. Фабрика
* гарантирует совместимость полученных продуктов. Обратите внимание, что
* сигнатуры методов Конкретной Фабрики возвращают абстрактный продукт, в то
* время как внутри метода создается экземпляр конкретного продукта.
*/

class ConcreteFactory1 : public AbstractFactory
{
public:
AbstractProductA* CreateProductA() const override
{
return new ConcreteProductA1();
}

AbstractProductB* CreateProductB() const override
{
return new ConcreteProductB1();
}
};
/**
* EN: Each Concrete Factory has a corresponding product variant.
*
* RU: Каждая Конкретная Фабрика имеет соответствующую вариацию продукта.
*/

class ConcreteFactory2 : public AbstractFactory
{
public:
AbstractProductA* CreateProductA() const override
{
return new ConcreteProductA2();
}

AbstractProductB* CreateProductB() const override
{
return new ConcreteProductB2();
}
};




/**
* EN: The client code works with factories and products only through abstract
* types: AbstractFactory and AbstractProduct. This lets you pass any factory or
* product subclass to the client code without breaking it.
*
* RU: Клиентский код работает с фабриками и продуктами только через абстрактные
* типы: Абстрактная Фабрика и Абстрактный Продукт. Это позволяет передавать
* любой подкласс фабрики или продукта клиентскому коду, не нарушая его.
*/

void ClientCode(const AbstractFactory& factory){
const AbstractProductA* product_a =factory.CreateProductA();
const AbstractProductB* product_b =factory.CreateProductB();
std::cout << product_b->UsefulFunctionB() << "\n";
std::cout << product_b->AnotherUsefulFunctionB(*product_a) << "\n";
delete product_a;
delete product_b;
}

int main(){
std::cout << "Client: Testing client code with the first factory type:\n";
ConcreteFactory1* f1= new ConcreteFactory1();
ClientCode(*f1);
delete f1;
std::cout << std::endl;
std::cout << "Client: Testing the same client code with the second factory type:\n";
ConcreteFactory2* f2= new ConcreteFactory2();
ClientCode(*f2);
delete f2;
return 0;
}
10 changes: 10 additions & 0 deletions src/Adapter/Conceptual/MultipleInheritance/Output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Client: I can work just fine with the Target objects:
Target: The default target's behavior.

Client: The Adaptee class has a weird interface. See, I don't understand it:
Adaptee: .eetpadA eht fo roivaheb laicepS

Client: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.


Loading