Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add patterns abstract fabric, builder and bridge
- Loading branch information
Showing
11 changed files
with
235 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
####Simple doc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
[Источник описания][source] | ||
|
||
####Абстрактная фабрика (Abstract factory) | ||
|
||
Порождающий шаблон проектирования, позволяющий изменять поведение системы, варьируя создаваемые объекты, при этом сохраняя интерфейсы. Он позволяет создавать целые группы взаимосвязанных объектов, которые, будучи созданными одной фабрикой, реализуют общее поведение. Шаблон реализуется созданием абстрактного класса Factory, который представляет собой интерфейс для создания компонентов системы (например, для оконного интерфейса он может создавать окна и кнопки). Затем пишутся наследующиеся от него классы, реализующие этот интерфейс. | ||
|
||
######Цель | ||
Предоставляет интерфейс для создания семейств взаимосвязанных или взаимозависимых объектов, не специфицируя их конкретных классов. | ||
######Плюсы | ||
* изолирует конкретные классы; | ||
* упрощает замену семейств продуктов; | ||
* гарантирует сочетаемость продуктов. | ||
######Минусы | ||
* сложно добавить поддержку нового вида продуктов. | ||
######Применимость | ||
* Система не должна зависеть от того, как создаются, компонуются и представляются входящие в нее объекты. | ||
* Входящие в семейство взаимосвязанные объекты должны использоваться вместе и вам необходимо обеспечить выполнение этого ограничения | ||
* Система должна конфигурироваться одним из семейств составляющих ее объектов. | ||
* Требуется предоставить библиотеку объектов, раскрывая только их интерфейсы, но не реализацию. | ||
|
||
|
||
[source]: http://ru.wikipedia.org/wiki/%D0%90%D0%B1%D1%81%D1%82%D1%80%D0%B0%D0%BA%D1%82%D0%BD%D0%B0%D1%8F_%D1%84%D0%B0%D0%B1%D1%80%D0%B8%D0%BA%D0%B0_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F)#.D0.9F.D1.80.D0.B8.D0.BC.D0.B5.D1.80_Ruby |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
# Создание фабрики для реализации 1 | ||
class RealisationFactory1 | ||
def create_button | ||
Realisation_1.new | ||
end | ||
end | ||
|
||
# Создание фабрики для реализации 2 | ||
class RealisationFactory2 | ||
def create_button | ||
Realisation_2.new | ||
end | ||
end | ||
|
||
# Базовый клас | ||
class BaseClass | ||
attr_accessor :caption | ||
end | ||
|
||
# Реализация класса | ||
class Realisation_1 < BaseClass | ||
def render | ||
puts "I`m Realisation_1 #{@caption}" | ||
end | ||
end | ||
|
||
# Реализация класса | ||
class Realisation_2 < BaseClass | ||
def render | ||
puts "I`m Realisation_2 #{@caption}" | ||
end | ||
end | ||
|
||
class Application | ||
def initialize(factory) | ||
button = factory.create_button | ||
button.caption = 'Start' | ||
button.render | ||
end | ||
end | ||
|
||
|
||
class ApplicationRunner | ||
def self.run | ||
Application.new(self.createSpecificFactory) | ||
end | ||
|
||
def self.createSpecificFactory | ||
if use_realisation_1 | ||
RealisationFactory1.new | ||
else | ||
RealisationFactory2.new | ||
end | ||
end | ||
end | ||
|
||
ApplicationRunner.run |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
class WinFactory | ||
def create_button | ||
WinButton.new | ||
end | ||
end | ||
|
||
class LinFactory | ||
def create_button | ||
LinButton.new | ||
end | ||
end | ||
|
||
class Button | ||
attr_accessor :caption | ||
end | ||
|
||
class WinButton < Button | ||
def render | ||
puts "I`m WinButton #{@caption}" | ||
end | ||
end | ||
|
||
class LinButton < Button | ||
def render | ||
puts "I`m LinButton #{@caption}" | ||
end | ||
end | ||
|
||
class Application | ||
def initialize(factory) | ||
button = factory.create_button | ||
button.caption = 'Start' | ||
button.render | ||
end | ||
end | ||
|
||
|
||
class ApplicationRunner | ||
def self.run | ||
Application.new(self.createOsSpecificFactory) | ||
end | ||
|
||
def self.createOsSpecificFactory | ||
if RUBY_PLATFORM.downcase.include?("mswin") | ||
WinFactory.new | ||
else | ||
LinFactory.new | ||
end | ||
end | ||
end | ||
|
||
ApplicationRunner.run |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
####Bridge |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# При частом изменении класса, преимущества объектно-ориентированного подхода становятся очень полезными, | ||
# позволяя делать изменения в программе, обладая минимальными сведениями о реализации программы. | ||
# Шаблон bridge является полезным там, где часто меняется не только сам класс, но и то, что он делает. | ||
|
||
module Bridge | ||
|
||
# Абстракция нашей реализации | ||
# определяем интерфейс абстракции | ||
# хранит ссылку на объект Implementor | ||
class Abstraction | ||
attr_accessor :implementator | ||
|
||
def info | ||
implementator.info | ||
end | ||
end | ||
|
||
# RefinedAbstraction - уточненная абстракция | ||
# расширяет интерфейс, определенный абстракцией Abstraction | ||
class RefinedAbstraction<Abstraction | ||
|
||
end | ||
|
||
# Implementor - реализатор | ||
# определяет интерфейс для классов реализации. Он не обязан точно | ||
# соотведствовать интерфейсу класса Abstraction. На самом деле оба | ||
# интерфейса могут быть совершенно различны. Обычно интерфейс класса | ||
# Implementor представляет только примитивные операции, а класс | ||
# Abstraction определяет операции более высокого уровня, | ||
# базирующиеся на этих примитивах | ||
class Implementor | ||
def info | ||
|
||
end | ||
end | ||
|
||
# ConcreteImplementor - конкретный реализатор | ||
# содержит конкретную реализацию интерфейса | ||
|
||
# Реализатор ConcreteImplementorA | ||
class ConcreteImplementorA<Implementor | ||
def info | ||
p "ConcreteImplementorA" | ||
end | ||
end | ||
|
||
# Реализатор ConcreteImplementorB | ||
class ConcreteImplementorB<Implementor | ||
def info | ||
p "ConcreteImplementorB" | ||
end | ||
end | ||
|
||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
module Sample | ||
module Bridge | ||
# Создаем нашу абстракцию | ||
class Abstraction | ||
attr_accessor :implementator | ||
|
||
def parse_data | ||
implementator.parse_data | ||
end | ||
end | ||
|
||
# Расширяем абстракцию создаем например класс Exchange | ||
# через который будем реализовывать обмен | ||
class Exchange<Abstraction | ||
|
||
end | ||
|
||
class Implementator | ||
|
||
def parse_data | ||
|
||
end | ||
end | ||
|
||
# Создаем реализацию обмена для 1С | ||
class OneC<Implementator | ||
def parse_data | ||
p "1c data" | ||
end | ||
end | ||
# Создаем реализацию обмена для Sclados | ||
class Sclados<Implementator | ||
def parse_data | ||
p "Sclados data" | ||
end | ||
end | ||
# Создаем реализацию обмена для Traider | ||
class Traider<Implementator | ||
def parse_data | ||
p "Traider data" | ||
end | ||
end | ||
|
||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
####Builder |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
#FILE SHOULD HAVE STRUCTURE PATTERN |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
#FILE SHOULD SAMPLE PATTERN |