The Adapter pattern is used to allow an existing Queue class to be used as a Stack. A ClassAdapter inherits from the Stack interface and the Queue class, implementing the stack operations by manipulating the underlying queue. An ObjectAdapter composes a Queue instance and implements the Stack interface by delegating to the queue's methods.
This document discusses the adapter pattern in object-oriented programming. The adapter pattern allows classes with incompatible interfaces to work together by converting the interface of one class into another interface that clients expect. An adapter acts as a bridge between two incompatible interfaces. It adapts the interface of an existing class (the adaptee) so that its interface conforms to what the client expects (the target interface). An example is provided where a class that sorts lists is adapted to sort arrays by converting between the list and array interfaces.
This document discusses design patterns and provides examples of the Singleton and Abstract Factory patterns. It begins with an introduction to design patterns, their purpose and history. It then discusses the Singleton pattern in detail using a logger example and describes how to implement it using lazy instantiation. It also covers the Abstract Factory pattern using real world examples of a kitchen and chefs. It compares how these patterns would be implemented in code versus real objects.
The adapter pattern converts the interface of one class into another interface that clients expect. It allows classes to work together that otherwise could not due to incompatible interfaces. There are two common implementations: class adapter uses inheritance to adapt the interface, while object adapter uses composition by delegating to the adapted class. The adapter pattern is useful for integration work to combine existing classes with mismatched interfaces.
The Adapter pattern is used to allow an existing Queue class to be used as a Stack. A ClassAdapter inherits from the Stack interface and the Queue class, implementing the stack operations by manipulating the underlying queue. An ObjectAdapter composes a Queue instance and implements the Stack interface by delegating to the queue's methods.
This document discusses the adapter pattern in object-oriented programming. The adapter pattern allows classes with incompatible interfaces to work together by converting the interface of one class into another interface that clients expect. An adapter acts as a bridge between two incompatible interfaces. It adapts the interface of an existing class (the adaptee) so that its interface conforms to what the client expects (the target interface). An example is provided where a class that sorts lists is adapted to sort arrays by converting between the list and array interfaces.
This document discusses design patterns and provides examples of the Singleton and Abstract Factory patterns. It begins with an introduction to design patterns, their purpose and history. It then discusses the Singleton pattern in detail using a logger example and describes how to implement it using lazy instantiation. It also covers the Abstract Factory pattern using real world examples of a kitchen and chefs. It compares how these patterns would be implemented in code versus real objects.
The adapter pattern converts the interface of one class into another interface that clients expect. It allows classes to work together that otherwise could not due to incompatible interfaces. There are two common implementations: class adapter uses inheritance to adapt the interface, while object adapter uses composition by delegating to the adapted class. The adapter pattern is useful for integration work to combine existing classes with mismatched interfaces.
The Proxy design pattern provides a surrogate or placeholder for another object to control access to it. A proxy can act as a placeholder for complex, expensive objects that should not be initialized until needed. This delays the creation of these objects until they are actually required. Proxies can also protect the real component from undue complexity or provide extra functionality. Some common uses of proxies include remote proxies for objects in a different address space, virtual proxies that create objects on demand, and protection proxies that control access to the original object.
The document discusses the Abstract Factory pattern, which defines an interface for creating families of related objects without specifying their concrete classes. It provides advantages like isolating code from implementation classes and promoting consistency. The implementation overview describes creating shape and color interfaces and classes, an AbstractFactory interface, and Factory classes that extend AbstractFactory and create shape and color objects. FactoryProducer is used to get the appropriate factory. Tests create objects using the factories to demonstrate the pattern.
in these slides i have explained the factory method design pattern. slides contains complete notes on this pattern from definition to implementation by code example.
The Command Pattern encapsulates requests as objects, allowing clients to parameterize requests and supporting undoable operations. It decouples the invoker of a request from the implementation of the request, making it possible to queue, log, and execute requests at different times. Some benefits include flexibility in specifying, queueing, and executing requests, as well as supporting undo functionality. Some potential liabilities include efficiency losses and an excessive number of command classes.
The Command pattern encapsulates a request as an object, allowing requests to be parameterized with different objects and queued or logged. A command object represents the method call and stores the method name, owner object, and parameters. A client creates a concrete command object and passes it to an invoker, which stores the command and calls its execute method, invoking the action on the receiver object. This decouples the requestor from the performer and allows invokers to be parameterized with different commands at runtime.
This document provides an overview of the SOLID principles of object-oriented design:
- SOLID is an acronym that stands for five design principles introduced by Robert C. Martin. The principles are Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion.
- Applying these principles helps make software more maintainable, reusable, and understandable by reducing coupling between modules and increasing cohesion within modules. This addresses issues like rigidity, fragility, and immobility that make code difficult to change over time.
- The principles should be applied when refactoring existing code that shows signs of rot, such as code smells, in order to remove these
The SOLID Principles Illustrated by Design PatternsHayim Makabee
The goal of the SOLID design principles is to improve the Separation of Concerns, through weaker Coupling and stronger Cohesion. The main consequence should be software systems that are easier to maintain and to extend. However the definition of the SOLID principles is quite abstract, and some developers find it difficult to apply them in practice. In my talk I will show how well-known Design Patterns illustrate the application of the SOLID principles, and also show examples of how to follow these principles to Refactor and improve existing designs.
About the speaker:
Hayim Makabee was born in Rio de Janeiro. He immigrated to Israel in 1992 and completed his M.Sc. studies on Computer Sciences at the Technion. Since then he worked for several hi-tech companies, including also some start-ups. Currently he is a co-founder of the International Association of Software Architects (IASA) in Israel. Hayim is the author of a book about Object-Oriented Programming and has published papers in the fields of Software Engineering, Distributed Systems and Genetic Algorithms.
This document discusses the facade design pattern. The facade pattern provides a simplified interface to a more complex subsystem. It decouples the subsystem from the client and makes the subsystem easier to use. A facade acts as a front-facing interface that hides the underlying complexities of the subsystem and delegates client requests to appropriate subsystem classes. This reduces dependencies between subsystems and promotes loose coupling. The facade pattern is useful for layering subsystems and simplifying access to them through a single interface.
The Visitor pattern allows new operations to be added to existing object structures without modifying those structures. It separates an object structure from the operations performed on it, allowing independent extension of both. Some key aspects include:
- Visitors define a visit operation for each element type in the object structure. Concrete visitors implement the operations.
- Elements contain an accept method to accept visitor operations. Concrete elements call the appropriate visit method.
- Clients traverse the structure and pass a visitor to each element's accept method.
The pattern allows encapsulation of new operations without changing element classes, and separates unrelated operations for elements. It can apply to structures without a shared hierarchy.
The visitor pattern represents an operation to be performed on elements of an object structure without changing the classes of the elements. It is used when there are many unrelated operations needed on the structure. In the visitor pattern, an operation is encapsulated in a visitor object that traverses the elements and performs the operation based on each element's type. This separates the operations from the element classes and makes adding new operations easier than changing each element class.
The Builder pattern is used to generate different types of reports (Crystal, HTML, PDF) from a CRM document format, while keeping the report construction process the same. An abstract ReportBuilder interface defines common report generation steps. Concrete builders like CrystalReportBuilder, HTMLReportBuilder, and PDFReportBuilder implement these steps to produce their specific report types. A ReportDirector coordinates the building process by working with a ReportBuilder object.
This document provides information about a course on design patterns taught by Dr. Asma Cherif. It includes the course code, instructor details, learning objectives, textbooks, and topics that will be covered such as architectural design, what patterns are, and different types of patterns. Design patterns provide solutions to common software design problems and promote reuse of successful designs. The course aims to help students understand design patterns, identify patterns in code and designs, and implement patterns to design and develop quality software applications.
This document discusses deployment slots on Azure, which allow developers to deploy new versions of an app to a staging slot and test it before swapping the staging slot into production. It explains that slots share app settings, connection strings, and other configuration but have separate code, allowing developers to test new code without affecting production. It also warns that slots may not be fully isolated, so care must be taken when using shared resources like databases. Developers are advised to use slots to minimize downtime and enable testing and rollback of new deployments.
This document provides an introduction to the MVVM design pattern. It describes MVVM as separating an application into three main parts: the Model, the View, and the ViewModel. The Model manages the data and business logic. The View displays the user interface. The ViewModel acts as an intermediary between the Model and View, providing the data and handling user input. Benefits of MVVM include loose coupling between components, testable code, and maintainable code. Some common MVVM frameworks are also listed.
The document provides an introduction and overview of design patterns. It defines design patterns as common solutions to recurring problems in software design. The document discusses the origin of design patterns in architecture, describes the four essential parts of a design pattern (name, problem, solution, consequences), and categorizes patterns into creational, structural, and behavioral types. Examples of commonly used patterns like Singleton and State patterns are also presented.
The Command design pattern encapsulates requests as objects, allowing for the parameterization of clients with different requests, queues of requests, and undo functionality. It decouples the invoker of a request from the receiver that performs it. Some key elements are the Command interface that declares an execute method, ConcreteCommand classes that link Receivers to their actions, and an Invoker that asks Commands to carry out requests. The pattern supports adding new commands without changing existing code but can lead to many command classes cluttering the design. It is used when objects need to issue parameterized requests without coupling to receivers or timing of requests.
Je vous partage l'un des présentations que j'ai réalisé lorsque j'étais élève ingénieur pour le module 'Anglais Business ' , utile pour les étudiants souhaitant préparer une présentation en anglais sur les Design Pattern - ou les patrons de conception .
The Proxy design pattern provides a surrogate or placeholder for another object to control access to it. A proxy can act as a placeholder for complex, expensive objects that should not be initialized until needed. This delays the creation of these objects until they are actually required. Proxies can also protect the real component from undue complexity or provide extra functionality. Some common uses of proxies include remote proxies for objects in a different address space, virtual proxies that create objects on demand, and protection proxies that control access to the original object.
The document discusses the Abstract Factory pattern, which defines an interface for creating families of related objects without specifying their concrete classes. It provides advantages like isolating code from implementation classes and promoting consistency. The implementation overview describes creating shape and color interfaces and classes, an AbstractFactory interface, and Factory classes that extend AbstractFactory and create shape and color objects. FactoryProducer is used to get the appropriate factory. Tests create objects using the factories to demonstrate the pattern.
in these slides i have explained the factory method design pattern. slides contains complete notes on this pattern from definition to implementation by code example.
The Command Pattern encapsulates requests as objects, allowing clients to parameterize requests and supporting undoable operations. It decouples the invoker of a request from the implementation of the request, making it possible to queue, log, and execute requests at different times. Some benefits include flexibility in specifying, queueing, and executing requests, as well as supporting undo functionality. Some potential liabilities include efficiency losses and an excessive number of command classes.
The Command pattern encapsulates a request as an object, allowing requests to be parameterized with different objects and queued or logged. A command object represents the method call and stores the method name, owner object, and parameters. A client creates a concrete command object and passes it to an invoker, which stores the command and calls its execute method, invoking the action on the receiver object. This decouples the requestor from the performer and allows invokers to be parameterized with different commands at runtime.
This document provides an overview of the SOLID principles of object-oriented design:
- SOLID is an acronym that stands for five design principles introduced by Robert C. Martin. The principles are Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion.
- Applying these principles helps make software more maintainable, reusable, and understandable by reducing coupling between modules and increasing cohesion within modules. This addresses issues like rigidity, fragility, and immobility that make code difficult to change over time.
- The principles should be applied when refactoring existing code that shows signs of rot, such as code smells, in order to remove these
The SOLID Principles Illustrated by Design PatternsHayim Makabee
The goal of the SOLID design principles is to improve the Separation of Concerns, through weaker Coupling and stronger Cohesion. The main consequence should be software systems that are easier to maintain and to extend. However the definition of the SOLID principles is quite abstract, and some developers find it difficult to apply them in practice. In my talk I will show how well-known Design Patterns illustrate the application of the SOLID principles, and also show examples of how to follow these principles to Refactor and improve existing designs.
About the speaker:
Hayim Makabee was born in Rio de Janeiro. He immigrated to Israel in 1992 and completed his M.Sc. studies on Computer Sciences at the Technion. Since then he worked for several hi-tech companies, including also some start-ups. Currently he is a co-founder of the International Association of Software Architects (IASA) in Israel. Hayim is the author of a book about Object-Oriented Programming and has published papers in the fields of Software Engineering, Distributed Systems and Genetic Algorithms.
This document discusses the facade design pattern. The facade pattern provides a simplified interface to a more complex subsystem. It decouples the subsystem from the client and makes the subsystem easier to use. A facade acts as a front-facing interface that hides the underlying complexities of the subsystem and delegates client requests to appropriate subsystem classes. This reduces dependencies between subsystems and promotes loose coupling. The facade pattern is useful for layering subsystems and simplifying access to them through a single interface.
The Visitor pattern allows new operations to be added to existing object structures without modifying those structures. It separates an object structure from the operations performed on it, allowing independent extension of both. Some key aspects include:
- Visitors define a visit operation for each element type in the object structure. Concrete visitors implement the operations.
- Elements contain an accept method to accept visitor operations. Concrete elements call the appropriate visit method.
- Clients traverse the structure and pass a visitor to each element's accept method.
The pattern allows encapsulation of new operations without changing element classes, and separates unrelated operations for elements. It can apply to structures without a shared hierarchy.
The visitor pattern represents an operation to be performed on elements of an object structure without changing the classes of the elements. It is used when there are many unrelated operations needed on the structure. In the visitor pattern, an operation is encapsulated in a visitor object that traverses the elements and performs the operation based on each element's type. This separates the operations from the element classes and makes adding new operations easier than changing each element class.
The Builder pattern is used to generate different types of reports (Crystal, HTML, PDF) from a CRM document format, while keeping the report construction process the same. An abstract ReportBuilder interface defines common report generation steps. Concrete builders like CrystalReportBuilder, HTMLReportBuilder, and PDFReportBuilder implement these steps to produce their specific report types. A ReportDirector coordinates the building process by working with a ReportBuilder object.
This document provides information about a course on design patterns taught by Dr. Asma Cherif. It includes the course code, instructor details, learning objectives, textbooks, and topics that will be covered such as architectural design, what patterns are, and different types of patterns. Design patterns provide solutions to common software design problems and promote reuse of successful designs. The course aims to help students understand design patterns, identify patterns in code and designs, and implement patterns to design and develop quality software applications.
This document discusses deployment slots on Azure, which allow developers to deploy new versions of an app to a staging slot and test it before swapping the staging slot into production. It explains that slots share app settings, connection strings, and other configuration but have separate code, allowing developers to test new code without affecting production. It also warns that slots may not be fully isolated, so care must be taken when using shared resources like databases. Developers are advised to use slots to minimize downtime and enable testing and rollback of new deployments.
This document provides an introduction to the MVVM design pattern. It describes MVVM as separating an application into three main parts: the Model, the View, and the ViewModel. The Model manages the data and business logic. The View displays the user interface. The ViewModel acts as an intermediary between the Model and View, providing the data and handling user input. Benefits of MVVM include loose coupling between components, testable code, and maintainable code. Some common MVVM frameworks are also listed.
The document provides an introduction and overview of design patterns. It defines design patterns as common solutions to recurring problems in software design. The document discusses the origin of design patterns in architecture, describes the four essential parts of a design pattern (name, problem, solution, consequences), and categorizes patterns into creational, structural, and behavioral types. Examples of commonly used patterns like Singleton and State patterns are also presented.
The Command design pattern encapsulates requests as objects, allowing for the parameterization of clients with different requests, queues of requests, and undo functionality. It decouples the invoker of a request from the receiver that performs it. Some key elements are the Command interface that declares an execute method, ConcreteCommand classes that link Receivers to their actions, and an Invoker that asks Commands to carry out requests. The pattern supports adding new commands without changing existing code but can lead to many command classes cluttering the design. It is used when objects need to issue parameterized requests without coupling to receivers or timing of requests.
Je vous partage l'un des présentations que j'ai réalisé lorsque j'étais élève ingénieur pour le module 'Anglais Business ' , utile pour les étudiants souhaitant préparer une présentation en anglais sur les Design Pattern - ou les patrons de conception .
Доклад Александра Макарова для Съесть собаку #10: PHP, 12/10/2017.
Тезисы:
- Что такое архитектура сайта и зачем она нужна
- Виноват ли фреймворк в плохой архитектуре
- Где выход из сложности и регрессий
- Что делать со сложным доменом
- Выводы.
Netpeak Group продолжает серию образовательных мероприятий — #NetpeakTalks в Одессе.
В рамках этих встреч у тебя будет возможность обсудить с практикующим спикером наболевшие темы, связанные с R&D, дизайном, менеджментом, интернет-маркетингом, QA, Customer Success, аналитикой и др. (все темы от встречи к встрече не повторяются и отличаются друг от друга).
Тема#3: Масштабируемое приложение на PHP
Краткий план:
1. Теория принципов и паттернов проектирования.
2. Примеры использования принципов и паттернов в коде (разберём какие "плюшки" даёт каждый случай).
3. Важность слабосвязанного кода (IoC).
4. Как "под капотом" работают IOC контейнера.
_____________________
Информацию об этом и следующих мероприятиях ты можешь отследить:
FaceBook: https://www.facebook.com/NetpeakTalks/
Телеграм: https://t.me/netpeaktalks
__________
Плейлист с выступлениями на YouTube: https://www.youtube.com/playlist?list=PL8LIMl0TjrcDtSS_lM5jqH-huK5FCq44A
__________
Лучшие практики для повышения надежности разрабатываемых вами систем начиная от организации командной разработки до автоматизации тестирования алгоритмов и применения формальных методов для доказательства отсутствия ошибок.
5. Х.., Х… - и на продакшен
Принципы ООП
• Абстракция
• Инкапсуляция
• Наследование
• Полиморфизм
Проектирование
Сначала определяются требования и создается
модель предметной области, затем добавляются
методы программных классов, описывающие
передачу сообщений между объектами для
удовлетворения требований.
6. GRASP - определение
General Responsibility Assignment Software Patterns
общие образцы распределения обязанностей
GRASP - паттерны, используемые в объектно-
ориентированном проектировании для решения
общих задач по назначению обязанностей
классам и объектам
7. GRASP
Методический подход к объектному проектированию
Паттерны
• Information Expert (Информационный эксперт)
• Creator (Создатель)
• Controller (Контроллер)
• Low Coupling (Слабая связанность)
• High Cohesion (Сильное Сцепление)
• Polymorphism (Полиморфизм)
• Pure Fabrication (Чистая выдумка)
• Indirection (Посредник)
• Protected Variations (Сокрытие реализации)
8. Information Expert
Информационный эксперт
Проблема: В системе должна аккумулироваться,
рассчитываться и т. п. необходимая информация.
Решение: Назначить обязанность аккумуляции
информации, расчета и т. п. некоему классу
(информационному эксперту), обладающему
необходимой информацией.
Рекомендации: Информационным экспертом
может быть не один класс, а несколько.
10. Information Expert
Преимущества
• Поддерживает инкапсуляцию, то есть объекты
используют свои собственные данные для
выполнения поставленных задач
• Поведение системы обеспечивается классами,
содержащими требуемую информацию.
Поддерживается High Cohesion
Недостатки
При проблемах со связыванием и зацеплением.
11. Creator
Проблема: "Кто" должен отвечать за создание
экземпляров класса ?
Решение: Назначить классу В обязанность
создавать объекты другого класса А
Рекомендации: применять паттерн если
• Класс B содержит или агрегирует объекты A.
• Класс B записывает экземпляры объектов A.
• Класс B активно использует объекты A
• Класс B обладает данными инициализации для
объектов A
12. Creator
Преимущества
• Использование этого паттерна не повышает
связанности, поскольку созданный класс, как
правило, виден только для класса - создателя.
Недостатки
Если процедура создания объекта достаточно
сложная (например выполняется на основе
некоего внешнего условия), логично использовать
паттерн "Абстрактная Фабрика", то есть,
делегировать обязанность создания объектов
специальному классу.
13. Low Coupling
Низкая связанность
Проблема: Как обеспечить низкую зависимость,
незначительное влияние изменений и повысить
возможность повторного использования?
Решение: Распределить обязанности таким
образом, чтобы степень связанности оставалась
низкой.
15. Low Coupling
Низкая связанность
Преимущества:
• Изменение компонентов мало сказывается на других
объектах
• Принципы работы и функции классов/компонентов
можно понять, не изучая другие объекты
• Удобство повторного использования
16. High Cohesion
Высокое зацепление
Проблема: Как обеспечить возможность управления
сложностью?
Решение: Обеспечить распределение обязанностей с
высокой степенью зацепления
Пример: Если на класс "Регистрация" возлагать все
новые и новые системные функции, связанные с
системными операциями, то данный класс будет слишком
перегружен и будет обладать низкой степенью
зацепления.
17. High Cohesion
Высокое зацепление
Преимущества: Классы с высокой степенью зацепления
просты в поддержке и повторном использовании.
Недостатки: Иногда бывает неоправданно использовать
высокое зацепление для распределенных серверных
объектов. В этом случае для обеспечения быстродействия
необходимо создать несколько более крупных серверных
объектов со слабым зацеплением.
18. Pure Fabrication
Чистая выдумка
Проблема: Какой класс должен обеспечивать реализацию
паттернов "Высокое зацепление", и "Низкая связанность"?
Решение: Присвоить группу обязанностей с высокой
степенью зацепления классу, который не представляет
конкретного понятия из предметной области.
Пример: Какой класс должен сохранять экземпляры
класса "Продажа" в реляционной базе данных?
19. Pure Fabrication
Чистая выдумка
Преимущества:
Класс "ПостоянноеХранилище" будет обладать низкой
степенью связывания и высокой степенью зацепления.
Недостатки:
Данным паттерном не следует злоупотреблять иначе все
функции системы превратятся в объекты.
20. GRASP
Методический подход к объектному проектированию
Паттерны
• Information Expert (Информационный эксперт)
• Creator (Создатель)
• Controller (Контроллер)
• Low Coupling (Слабая связанность)
• High Cohesion (Сильное Сцепление)
• Polymorphism (Полиморфизм)
• Pure Fabrication (Чистая выдумка)
• Indirection (Посредник)
• Protected Variations (Сокрытие реализации)