Skip to content

Add factory method pattern. #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 0.20.0
- Add "Conceptual Dialog Factory" example.

## 0.19.0
- Add "Conceptual Gui Factory" example.

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ It contains **Dart** examples for all classic **GoF** design patterns.

# Implementation checklist:
- [ ] **Creation**
- [ ] **Abstract Factory** [[Conceptual Gui Factory](https://github.com/RefactoringGuru/design-patterns-dart/tree/main/patterns/abstract_factory/conceptual_gui_factory)]
- [x] **Abstract Factory** [[Conceptual Gui Factory](https://github.com/RefactoringGuru/design-patterns-dart/tree/main/patterns/abstract_factory/conceptual_gui_factory)]
- [x] **Builder** - [[Color Text Format](https://github.com/RefactoringGuru/design-patterns-dart/tree/main/patterns/builder/color_text_format)]
- [ ] **Factory Method**
- [x] **Factory Method** [[Conceptual Platform Dialog](https://github.com/RefactoringGuru/design-patterns-dart/tree/main/patterns/factory_method/conceptual_platform_dialog)]
- [x] **Prototype** - [[Shapes](https://github.com/RefactoringGuru/design-patterns-dart/tree/main/patterns/prototype/shapes)]
- [ ] **Singleton**
- [ ] **Behavioral**
Expand Down
39 changes: 39 additions & 0 deletions patterns/factory_method/concaptual_platform_dialog/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Abstract Factory pattern
Factory Method is a creational design pattern that provides an interface for creating objects in a
superclass, but allows subclasses to alter the type of objects that will be created.

Tutorial: [here](https://refactoring.guru/design-patterns/factory-method).

### About example.
This the very conceptual example rewrite from original source code [java example](https://github.com/RefactoringGuru/design-patterns-java/tree/main/src/refactoring_guru/factory_method/example)

### Diagram:
![image](https://user-images.githubusercontent.com/8049534/166105090-a2b490fe-3e3e-44f1-a781-9777023020fb.png)

### Client code:
```dart
late Dialog dialog;

void main() {
configure();
runBusinessLogic();
}

void configure() {
if (Platform.isWindows) {
dialog = WindowsDialog();
} else {
dialog = HtmlDialog();
}
}

void runBusinessLogic() {
dialog.renderWindow();
}
```

### Output:
```
Windows Button
Click! Button says - "Hello World!"
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/// EN: Common interface for all buttons.
///
/// RU: Общий интерфейс для всех продуктов.
abstract class Button {
final void Function() onClick;

Button(this.onClick);

void render();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import 'button.dart';

/// EN: HTML button implementation.
///
/// RU: Реализация HTML кнопок.
class HtmlButton extends Button {
HtmlButton(void Function() onClick) : super(onClick);

@override
void render() {
print('<button>Test Button</button>');
onClick();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import 'button.dart';

/// EN: Windows button implementation.
///
/// RU: Реализация нативных кнопок операционной системы.
class WindowsButton extends Button {
WindowsButton(void Function() onClick) : super(onClick);

@override
void render() {
print('Windows Button');
onClick();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import '../buttons/button.dart';

abstract class Dialog {
void renderWindow() {
/// EN: ... other code ...
///
/// RU: ... остальной код диалога ...

Button okButton = createButton(() {
print('Click! Button says - "Hello World!"');
});
okButton.render();
}

/// EN: Subclasses will override this method in order to create specific
/// button objects.
///
/// RU: Подклассы будут переопределять этот метод, чтобы создавать конкретные
/// объекты продуктов, разные для каждой фабрики.
Button createButton(void Function() onClick);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import '../buttons/button.dart';
import '../buttons/html_button.dart';
import 'dialog.dart';

/// EN: HTML Dialog will produce HTML buttons.
///
/// RU: HTML-диалог.
class HtmlDialog extends Dialog {
@override
Button createButton(void Function() onClick) => HtmlButton(onClick);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import '../buttons/button.dart';
import '../buttons/windows_button.dart';
import 'dialog.dart';

/// EN: Windows Dialog will produce Windows buttons.
///
/// RU: Диалог на элементах операционной системы.
class WindowsDialog extends Dialog {
@override
Button createButton(void Function() onClick) => WindowsButton(onClick);
}
36 changes: 36 additions & 0 deletions patterns/factory_method/concaptual_platform_dialog/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import 'dart:io';

import 'dialogs_factory/dialog.dart';
import 'dialogs_factory/html_dialog.dart';
import 'dialogs_factory/windows_dialog.dart';

late Dialog dialog;

void main() {
configure();
runBusinessLogic();
}

/// EN: The concrete factory is usually chosen depending on configuration or
/// environment options.
///
/// RU: Приложение создаёт определённую фабрику в зависимости от конфигурации
/// или окружения.
void configure() {
if (Platform.isWindows) {
dialog = WindowsDialog();
} else {
dialog = HtmlDialog();
}
}

/// EN: All of the client code should work with factories and products
/// through abstract interfaces. This way it does not care which factory it
/// works with and what kind of product it returns.
///
/// RU: Весь остальной клиентский код работает с фабрикой и продуктами только
/// через общий интерфейс, поэтому для него неважно какая фабрика была
/// создана.
void runBusinessLogic() {
dialog.renderWindow();
}
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: design_patterns_dart
description: Dart examples for all classic GoF design patterns.
version: 0.19.0
version: 0.20.0
homepage: https://refactoring.guru/design-patterns
repository: https://github.com/RefactoringGuru/design-patterns-dart
issue_tracker: https://github.com/RefactoringGuru/design-patterns-dart/issue
Expand Down