SlideShare uma empresa Scribd logo
1 de 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]

Mais conteúdo relacionado

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

GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay IntroductionChen-Tsu Lin
 
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
 

Semelhante a OO Design with C++: 5. Design Principles, part 2 (20)

GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay Introduction
 
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
 
Gpus graal
Gpus graalGpus graal
Gpus graal
 

Mais 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
 

Mais 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
 

Último

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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Último (20)

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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

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.