SlideShare une entreprise Scribd logo
1  sur  18
C++ : принципы проектирования, часть 2 Дмитрий Штилерман, Рексофт
Основные принципы проектирования иерархий классов ,[object Object],[object Object],[object Object],[object Object]
The Open-Closed Principle (OCP) ,[object Object],[object Object],[object Object]
OCP - простой конкретный пример (1) struct Shape {ShapeType type; Rect bounds;}; void DrawShapes(Shape shapes[], int count)  {   for(int i = 0; i < count; i++)   switch(shapes[i])   {   case Circle:    DrawCircle(shapes[i].bounds); break;   case Rectangle:   DrawRectangle(shapes[i].bounds); break;   }  } Процедурный стиль. Как добавить новый тип фигуры? ???
[object Object],OCP - простой конкретный пример (2) class Shape {public: virtual void draw() = 0;}; class Circle : public Shape {void draw();}; class Rectangle : public Shape {void draw();}; void DrawShapes(std::vector<Shape*>& v)  {   std::vector<Shape*>::iterator itr;   for(itr = v.begin(); itr != v.end(); itr++)   (*itr)->draw();  } Добавление нового типа фигуры не меняет старый код.
OCP -  простой абстрактный пример Поведение клиента зависит от конкретного класса сервера и не может быть изменено без изменения исходного кода клиента Поведение клиента может быть изменено путем использования разных реализаций сервера
OCP - strategic closure (1) ,[object Object],class Shape {public: virtual void draw() = 0;}; class Circle : public Shape {void draw();}; class Rectangle : public Shape {void draw();}; void DrawShapes(std::vector<Shape*>& v)  {   std::vector<Shape*>::iterator itr;   for(itr = v.begin(); itr != v.end(); itr++)   (*itr)->draw();  } Новое требование: все круги рисовать до всех прямоугольников. ???
OCP - strategic closure (2) ,[object Object],[object Object],[object Object]
The Liskov Substitution Principle (LSP) ,[object Object],[object Object]
Пример н арушения  LSP - RTTI class Person {}; class Student : public Person {}; class Teacher : public Person {}; void processStudent(Student& student); void processTeacher(Teacher& teacher); void processPerson(Person& person)  {   if(typeid(person) == typeid(Student))   processStudent(static_cast<Student&>(person));   else if(typeid(person) == typeid(Teacher))   processTeacher(static_cast<Teacher&>(person));  } class SysAdmin : public Person {}; processPerson is broken!
Пример н арушения  LSP -  нарушение контракта class Rectangle  {   public:   int getHeight() const;   virtual void setHeight(int);   int getWidth() const;   virtual void setWidth(int);  }; void RectangleTest(Rectangle& r)  {   r.setHeight(4);    r.setWidth(5);   int S = r.getHeight()*r.getWidth();    assert(S==20);   } class Square : public Rectangle  {   public:   void setHeight(int h)   {   Rectangle::setHeight(h);   Rectangle::setWidth(h);   }   void setWidth(int w)   {   Rectangle::setWidth(w);   Rectangle::setHeight(w);   }  };
Design By Contract (DBC) ,[object Object],[object Object],[object Object]
DBC -  анализ примера class Rectangle  {   public:   int getHeight() const;   virtual void setHeight(int);   int getWidth() const;   virtual void setWidth(int);  }; class Square : public Rectangle  {   public:   void setHeight(int h)   {   Rectangle::setHeight(h);   Rectangle::setWidth(h);   }   void setWidth(int w)   {   Rectangle::setWidth(w);   Rectangle::setHeight(w);   }  }; Square::setHeight(h) postcondition: getHeight() == h getWidth() == h Square::setWidth(w) postcondition: getWidth() == w getHeight() == w Rectangle::setHeight(h) postcondition: getHeight() == h getWidth() unchanged Rectangle::setWidth(w) postcondition: getWidth() == w getHeight() unchanged
The Dependency Inversion Principle (DIP) ,[object Object],[object Object],[object Object]
DIP -  простой пример Клиент напрямую зависит от класса сервера и не может быть использован отдельно от него. Клиент зависит от абстрактного интерфейса  Почему dependency inversion?  Простой ответ: разворот стрелочек у серверных классов. Более сложный ответ: см ниже.
DIP -  проектирование многоуровневых систем (1) ,[object Object],[object Object],[object Object]
DIP -  проектирование многоуровневых систем (2) DIP  позволяет решить описанные проблемы.
The Interface Segregation Principle (ISP) ,[object Object],[object Object],[object Object]

Contenu connexe

Similaire à OO Design with C++: 5. Design Principles, part 2

GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay IntroductionChen-Tsu Lin
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfVishalKumarJha10
 
3D Design with OpenSCAD
3D Design with OpenSCAD3D Design with OpenSCAD
3D Design with OpenSCADVickyTGAW
 
OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1Dmitry Stillermann
 
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2StanfordComputationalImaging
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksJinTaek Seo
 
Vlsi ii project presentation
Vlsi ii project presentationVlsi ii project presentation
Vlsi ii project presentationRedwan Islam
 
Zarzadzanie pamiecia w .NET - WDI
Zarzadzanie pamiecia w .NET - WDIZarzadzanie pamiecia w .NET - WDI
Zarzadzanie pamiecia w .NET - WDIKonrad Kokosa
 
GPU Accelerated Domain Decomposition
GPU Accelerated Domain DecompositionGPU Accelerated Domain Decomposition
GPU Accelerated Domain DecompositionRichard Southern
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingMark Kilgard
 
Software Engineering for Indies #gcmuc18
Software Engineering for Indies #gcmuc18Software Engineering for Indies #gcmuc18
Software Engineering for Indies #gcmuc18Andreas Pohl
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Robert Schadek
 
Overlap Layout Consensus assembly
Overlap Layout Consensus assemblyOverlap Layout Consensus assembly
Overlap Layout Consensus assemblyZhuyi Xue
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manualVivek Kumar Sinha
 

Similaire à OO Design with C++: 5. Design Principles, part 2 (20)

GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay Introduction
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
 
3D Design with OpenSCAD
3D Design with OpenSCAD3D Design with OpenSCAD
3D Design with OpenSCAD
 
05-Debug.pdf
05-Debug.pdf05-Debug.pdf
05-Debug.pdf
 
OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1
 
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
 
Vlsi ii project presentation
Vlsi ii project presentationVlsi ii project presentation
Vlsi ii project presentation
 
Zarzadzanie pamiecia w .NET - WDI
Zarzadzanie pamiecia w .NET - WDIZarzadzanie pamiecia w .NET - WDI
Zarzadzanie pamiecia w .NET - WDI
 
GPU Accelerated Domain Decomposition
GPU Accelerated Domain DecompositionGPU Accelerated Domain Decomposition
GPU Accelerated Domain Decomposition
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and Culling
 
Multivariate outlier detection
Multivariate outlier detectionMultivariate outlier detection
Multivariate outlier detection
 
Software Engineering for Indies #gcmuc18
Software Engineering for Indies #gcmuc18Software Engineering for Indies #gcmuc18
Software Engineering for Indies #gcmuc18
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...
 
Overlap Layout Consensus assembly
Overlap Layout Consensus assemblyOverlap Layout Consensus assembly
Overlap Layout Consensus assembly
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
 
MapReduce Algorithm Design
MapReduce Algorithm DesignMapReduce Algorithm Design
MapReduce Algorithm Design
 

Plus de Dmitry Stillermann

Как расти самому, помогая расти другим — практическое применение Management T...
Как расти самому, помогая расти другим — практическое применение Management T...Как расти самому, помогая расти другим — практическое применение Management T...
Как расти самому, помогая расти другим — практическое применение Management T...Dmitry Stillermann
 
OO Design with C++: 4. Design Principles, part 1
OO Design with C++: 4. Design Principles, part 1OO Design with C++: 4. Design Principles, part 1
OO Design with C++: 4. Design Principles, part 1Dmitry Stillermann
 
OO Design with C++: 3. Inheritance, part 3
OO Design with C++: 3. Inheritance, part 3OO Design with C++: 3. Inheritance, part 3
OO Design with C++: 3. Inheritance, part 3Dmitry Stillermann
 
OO Design with C++: 2. Inheritance, part 2
OO Design with C++: 2. Inheritance, part 2OO Design with C++: 2. Inheritance, part 2
OO Design with C++: 2. Inheritance, part 2Dmitry Stillermann
 
OO Design with C++: 6. Templates & Patterns
OO Design with C++: 6. Templates & PatternsOO Design with C++: 6. Templates & Patterns
OO Design with C++: 6. Templates & PatternsDmitry Stillermann
 

Plus de Dmitry Stillermann (7)

DiSC Model in Practice
DiSC Model in PracticeDiSC Model in Practice
DiSC Model in Practice
 
Как расти самому, помогая расти другим — практическое применение Management T...
Как расти самому, помогая расти другим — практическое применение Management T...Как расти самому, помогая расти другим — практическое применение Management T...
Как расти самому, помогая расти другим — практическое применение Management T...
 
OO Design with C++: 4. Design Principles, part 1
OO Design with C++: 4. Design Principles, part 1OO Design with C++: 4. Design Principles, part 1
OO Design with C++: 4. Design Principles, part 1
 
OO Design with C++: 3. Inheritance, part 3
OO Design with C++: 3. Inheritance, part 3OO Design with C++: 3. Inheritance, part 3
OO Design with C++: 3. Inheritance, part 3
 
OO Design with C++: 2. Inheritance, part 2
OO Design with C++: 2. Inheritance, part 2OO Design with C++: 2. Inheritance, part 2
OO Design with C++: 2. Inheritance, part 2
 
OO Design with C++: 6. Templates & Patterns
OO Design with C++: 6. Templates & PatternsOO Design with C++: 6. Templates & Patterns
OO Design with C++: 6. Templates & Patterns
 
OO Design with C++: 0. Intro
OO Design with C++: 0. IntroOO Design with C++: 0. Intro
OO Design with C++: 0. Intro
 

Dernier

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Dernier (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

OO Design with C++: 5. Design Principles, part 2

  • 1. C++ : принципы проектирования, часть 2 Дмитрий Штилерман, Рексофт
  • 2.
  • 3.
  • 4. OCP - простой конкретный пример (1) struct Shape {ShapeType type; Rect bounds;}; void DrawShapes(Shape shapes[], int count) { for(int i = 0; i < count; i++) switch(shapes[i]) { case Circle: DrawCircle(shapes[i].bounds); break; case Rectangle: DrawRectangle(shapes[i].bounds); break; } } Процедурный стиль. Как добавить новый тип фигуры? ???
  • 5.
  • 6. OCP - простой абстрактный пример Поведение клиента зависит от конкретного класса сервера и не может быть изменено без изменения исходного кода клиента Поведение клиента может быть изменено путем использования разных реализаций сервера
  • 7.
  • 8.
  • 9.
  • 10. Пример н арушения LSP - RTTI class Person {}; class Student : public Person {}; class Teacher : public Person {}; void processStudent(Student& student); void processTeacher(Teacher& teacher); void processPerson(Person& person) { if(typeid(person) == typeid(Student)) processStudent(static_cast<Student&>(person)); else if(typeid(person) == typeid(Teacher)) processTeacher(static_cast<Teacher&>(person)); } class SysAdmin : public Person {}; processPerson is broken!
  • 11. Пример н арушения LSP - нарушение контракта class Rectangle { public: int getHeight() const; virtual void setHeight(int); int getWidth() const; virtual void setWidth(int); }; void RectangleTest(Rectangle& r) { r.setHeight(4); r.setWidth(5); int S = r.getHeight()*r.getWidth(); assert(S==20); } class Square : public Rectangle { public: void setHeight(int h) { Rectangle::setHeight(h); Rectangle::setWidth(h); } void setWidth(int w) { Rectangle::setWidth(w); Rectangle::setHeight(w); } };
  • 12.
  • 13. DBC - анализ примера class Rectangle { public: int getHeight() const; virtual void setHeight(int); int getWidth() const; virtual void setWidth(int); }; class Square : public Rectangle { public: void setHeight(int h) { Rectangle::setHeight(h); Rectangle::setWidth(h); } void setWidth(int w) { Rectangle::setWidth(w); Rectangle::setHeight(w); } }; Square::setHeight(h) postcondition: getHeight() == h getWidth() == h Square::setWidth(w) postcondition: getWidth() == w getHeight() == w Rectangle::setHeight(h) postcondition: getHeight() == h getWidth() unchanged Rectangle::setWidth(w) postcondition: getWidth() == w getHeight() unchanged
  • 14.
  • 15. DIP - простой пример Клиент напрямую зависит от класса сервера и не может быть использован отдельно от него. Клиент зависит от абстрактного интерфейса Почему dependency inversion? Простой ответ: разворот стрелочек у серверных классов. Более сложный ответ: см ниже.
  • 16.
  • 17. DIP - проектирование многоуровневых систем (2) DIP позволяет решить описанные проблемы.
  • 18.