SlideShare ist ein Scribd-Unternehmen logo
1 von 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]

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
🐬 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
 
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
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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
 

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.