Design Patterns Zsolt Tóth - University of Miskolctothzs/edu/design...Principles & Laws SOLID SOLID...
Transcript of Design Patterns Zsolt Tóth - University of Miskolctothzs/edu/design...Principles & Laws SOLID SOLID...
PrinciplesDesign Patterns
Zsolt Tóth
University of Miskolc
2017
Zsolt Toth (UM) Principles 2017 1 / 31
Introduction
Principlesemphasize the key concepts.can answer the question "Why ...?"always have to be born in mind.affect on everything.
Architecturesallow the modeling of software systems.facilitate the design of big systems.
Architectural Patternsgive a general solution for frequent problems.
Zsolt Toth (UM) Principles 2017 2 / 31
Principles & Laws
Outline
1 Principles & LawsOOPSOLIDDesign Laws
2 Software ArchitecturesCentralized Systems
Client - Server Modeln-Tier Architecture
Distributed SystemsService Oriented ArchitectureMicro services
3 Architectural Patterns
Zsolt Toth (UM) Principles 2017 3 / 31
Principles & Laws OOP
Basics of Object Oriented Programming
ClassObjectInheritancePolymorphismEncapsulationInformation HidingMessage
Static Type vs Dynamic TypeLate BindingAbstract class vs InterfaceSpecialization vsEncapsulationScopesInstances
Zsolt Toth (UM) Principles 2017 4 / 31
Principles & Laws SOLID
SOLID
Basic Principles of ObjectOriented DesignApplied TogetherAffect on Design PatternsLanguage IndependentRobert C. MartinEarly 2000
Single fesponsibility PrincipleOpen-Close PrincipleLiskov Substitution PrincipleInterface Segregation PrincipleDependency Inversion Principle
Zsolt Toth (UM) Principles 2017 5 / 31
Principles & Laws SOLID
Single Responsibility Principle
"A class should have only one reason to change."
Consequences+ Simple classes and methods+ Easy-to-understand+ Improve Code Quality+ Facilitate testing- More classes- Difficult to stick to it.
While a Button has state, text, iconand callback function,
it is rendered by the currentGUI Engine.the event is forwarded to itscallback function, when theButton is clicked.
Zsolt Toth (UM) Principles 2017 6 / 31
Principles & Laws SOLID
Open-Close Principle
"Software entities (classes, modules, functions, etc.) shouldbe open for extension, but closed for modification."
ConsequencesDo not override!Polymorphism
+ Abstraction+ Stable behavior+ Better interface design- No overriding
abstract class Template{
abstract void method1();abstract void method2();
final voidtemplateMethod(){
method1();method2();}
}
Zsolt Toth (UM) Principles 2017 7 / 31
Principles & Laws SOLID
Liskov Substitution Principle
"A variable v should be substituted by any object whosedynamic type is a subtype of the static type of v withoutchanging its desired properties."
Static types areas abstract as possible.as concrete as necessary.
+ Re-usability+ Abstractness- Well-designed class hierarchy
required
CollectionsListSetMapQueueStack
Differences?
Zsolt Toth (UM) Principles 2017 8 / 31
Principles & Laws SOLID
Interface Segregation Principle
"Provide as small and specific interfaces to the client as theyare needed."
+ Abstractness+ Loose coupling+ Smaller interfaces- More interfaces
Service definitionComponent based designFacade
Zsolt Toth (UM) Principles 2017 9 / 31
Principles & Laws SOLID
Dependency Inversion Principle
"Abstractions should not depend on details. Details shoulddepend on abstractions."
Use interfacesAsk dependencies, do notinstantiate them.
+ Facilitate testing+ Decoupling+ Re-usability- More interfaces to maintain- Inverts the thinking
Constructor definitionpublicprotected
MockingInterface and implementationshould be separated.Database Connectivity
Zsolt Toth (UM) Principles 2017 10 / 31
Principles & Laws Design Laws
Divide and Conquer
Whole is greater than the sum of its parts.
Politics, Warfare, ...Engineering
Interior DesignHeating systemIKEA Furniture
Mechanical PartsCogs, Pulley
CircuitsAD/DA ConverterAmplifiers
Software ComponentsSubsystemsDBMSs
AlgorithmsParallelism
More functionsCategorize - PartitioningSubsystems
More complexAnalyze - Define StepsMore simple, easierStill could be complex
RecursionReplaceable parts
MaintenanceAssembly
Additional CostAdministrationQuality Assurance
Zsolt Toth (UM) Principles 2017 11 / 31
Principles & Laws Design Laws
Pareto Principle
For many events, roughly 80% of the effects come from 20%of the causes.
80/20 ruleLaw of the vital fewEconomy & BusinessSoftware Engineering
Bug fixingLoad testingOptimization
Software ProjectsEasy to start
Let’s rewrite!Hard to finish
Testing, Documentation, ...
Usually unfinished"It satisfies industrial needs."
Full of bugs.Unprofessional work.Poor design.But someone pays for it.
Zsolt Toth (UM) Principles 2017 12 / 31
Principles & Laws Design Laws
KISS
Keep It Simple, Stupid!
U. S. Navy1960sSimplicityOccam’s Razor
In Software EngineeringLimit of class / method sizeDesign specific toolsUnix commandsCombine them
Zsolt Toth (UM) Principles 2017 13 / 31
Principles & Laws Design Laws
Don’t Repeat Yourself
Eliminate redundancyRe-usabilityAbstractionRefactoringctrl+c, ctrl+v
ExceptionsPerformance Issues
Database ReplicationsSecurity Issues
RAID
Zsolt Toth (UM) Principles 2017 14 / 31
Principles & Laws Design Laws
Gartner Hype Cycle - Amara’s Law
Zsolt Toth (UM) Principles 2017 15 / 31
Principles & Laws Design Laws
Brook’s Law
Adding manpower to a late software project makes it later"
Project ManagementTakes time to becomeproductiveCommunication overheadO(n2)
The mythical man-month
AgileTest Driven DevelopmentScrum
Sprint 2-4 weeksTeam ≈8 member
Zsolt Toth (UM) Principles 2017 16 / 31
Software Architectures
Outline
1 Principles & LawsOOPSOLIDDesign Laws
2 Software ArchitecturesCentralized Systems
Client - Server Modeln-Tier Architecture
Distributed SystemsService Oriented ArchitectureMicro services
3 Architectural Patterns
Zsolt Toth (UM) Principles 2017 17 / 31
Software Architectures
Software Architectures
Abstract structure of SoftwareSystemsIndependent of
PlatformProgramming Language
Depend onProject Goal
Purpose of the SystemScalability
Target Users1, 100, 10.000, ...Expected usage?Expected load?
Zsolt Toth (UM) Principles 2017 18 / 31
Software Architectures Centralized Systems
Monolithic Architecture
Only one processInstalled on a single computer
MainframesDesktop Applications
Unix commandsls, ln, ps, mkdir,grep, chmod, chown
Computer Games, WordprocessorsOff-line workInstallationComplex computationsOur first programs
+ Simple, easy-to-understandthe Architecture
+ Independent from otherapplications
+ Self-contained- Unmaintainable Application- No Modularity
Zsolt Toth (UM) Principles 2017 19 / 31
Software Architectures Centralized Systems
Component Based Design
Independent developmentunitA part of the systemProvide service via itsinterfaceUse other components
TestsUnitComponentIntegration
DependenciesBuild processDeployment
Zsolt Toth (UM) Principles 2017 20 / 31
Software Architectures Centralized Systems
Client - Server Model
Simple ModelClients request servicesServer waits for and servesrequests
Widely usedFTP, SSHWWW, SMTP
Web ApplicationsInformation SystemsSearch EnginesSocial MediaWeb Shopse–Governmente–BankingMonitoring Systems
Zsolt Toth (UM) Principles 2017 21 / 31
Software Architectures Centralized Systems
n-Tier ArchitectureDetailed than Client–ServerModelTiers are not LayersTiers have specific functions,purposeTypical tiers
PresentationClient–sideWeb sitesMobile / Desktopapplications
BusinessServer–sideBusiness logic
DatabaseServer–sideNot available directly.
Zsolt Toth (UM) Principles 2017 22 / 31
Software Architectures Distributed Systems
Service Oriented Architecture
Collection of ServicesService - Servicecommunication
Simple data passingCoordinating some activity
SolutionsCORBADCOMWeb Services
A servicerepresents an activity.is self-contained.is black box.may use other services.
Zsolt Toth (UM) Principles 2017 23 / 31
Software Architectures Distributed Systems
Micro services
Micro service is a process.Implementation of SOA.Popular since 2014.Characteristics
Fine-grainedCloud applicationsContinuous delivery
Reusability of services.
EMailServiceEmail notifications arerequired in many businessactivities.Each email has the samestructure.
sender, receiver addressessubjectcontent (generated by otherservices)
Zsolt Toth (UM) Principles 2017 24 / 31
Architectural Patterns
Outline
1 Principles & LawsOOPSOLIDDesign Laws
2 Software ArchitecturesCentralized Systems
Client - Server Modeln-Tier Architecture
Distributed SystemsService Oriented ArchitectureMicro services
3 Architectural Patterns
Zsolt Toth (UM) Principles 2017 25 / 31
Architectural Patterns
Model View Controller
Separation of value andappearanceDesktop applicationsWeb applicationsVariants
Model View PresenterModel View ViewModel
ModelDomain objectsState
ViewGraphical appearanceVisualization
ControllerConnection between modeland viewRefresh the ViewUser interactionsEvent handlers
Zsolt Toth (UM) Principles 2017 26 / 31
Architectural Patterns
Data Access Object
Abstract interface for persistence storageSeparation of persistence and businesslogicStorage IndependentFacilitates usage of different DBMSsDefines expected behaviorMultiple specific implementations
Typical methodsCreateReadUpdateDelete
Zsolt Toth (UM) Principles 2017 27 / 31
Architectural Patterns
Data Transfer Object
Messaging between systems.Separates
internal domain objectsexternal environment
Hides sensitive dataReduce network trafficRequest - Response ObjectsMarshalling
{"coordinate": {"x": 0, "y": 0, "z": 0},
5 "zone": {"id":
"00000000-0000-0000","name": "Unknown"},"uuid":
"2ee1f927-50af-45c9"10 }
Zsolt Toth (UM) Principles 2017 28 / 31
Architectural Patterns
Service Locator
Dependency InjectionEliminate dependency onimplementationCentral Registry of Services
CentralizedSingle "vague" dependencyEasy-to-understandDifficult testing
Loosely coupled ServicesRun-time linkerSingle Service LocatorRequest ServicesSimple, Reusable Services.
Zsolt Toth (UM) Principles 2017 29 / 31
Architectural Patterns
Interceptor
Modify a service requestTransparentUsage
ConversionFiltering
ExamplesWeb Server CGIJava EE, FiltersSpring Security
Zsolt Toth (UM) Principles 2017 30 / 31
Architectural Patterns
Publish Subscribe
Messaging PatternMessage Queue
Sendercreates messages.puts them to the queue.
Receiverchecks the queue.consumes messages.
Queuesharedordered
IPC
Publish SubscribePublisher
creates message.publish it in certaintopics.
Subscribersubscribes to topics.checks the topics.
Topicsknows both publishers &subscribersforwards messages
Alerts
Zsolt Toth (UM) Principles 2017 31 / 31