architectural patterns and software architectures: client-server, multi-tier, mvc, mvp, mvvm, ioc,...
Post on 10-May-2015
31.498 Views
Preview:
DESCRIPTION
TRANSCRIPT
Architectural Architectural PatternsPatterns
Multi-Tier, MVC, MVP, MVVM, IoC, DI, Multi-Tier, MVC, MVP, MVVM, IoC, DI, SOASOA
Svetlin Svetlin NakovNakovTelerik Telerik CorporationCorporationwww.telerik.
com
Table of ContentsTable of Contents
1.1. What is Software Architecture?What is Software Architecture?
2.2. Client-Server ArchitectureClient-Server Architecture
3.3. 3-Tier / Multi-Tier Architectures3-Tier / Multi-Tier Architectures
4.4. MVC (Model-View-Controller)MVC (Model-View-Controller)
5.5. MVP (Model-View-Presenter)MVP (Model-View-Presenter)
6.6. MVVM (Model-View-ViewModel)MVVM (Model-View-ViewModel)
7.7. IoC (Inversion of Control) and DI IoC (Inversion of Control) and DI (Dependency Injection) Architectural (Dependency Injection) Architectural PrincipalsPrincipals
8.8. SOA (Service-Oriented Architecture)SOA (Service-Oriented Architecture)2
What is Software What is Software Architecture?Architecture?
Software ArchitectureSoftware Architecture Software architecture Software architecture is a technical is a technical
blueprint explaining how the system blueprint explaining how the system will be structuredwill be structured
The The system architecturesystem architecture describesdescribes:: How the system will be decomposed How the system will be decomposed
into subsystems (modules)into subsystems (modules) Responsibilities of each moduleResponsibilities of each module Interaction between the modulesInteraction between the modules Platforms and technologiesPlatforms and technologies
Each module could also implement a Each module could also implement a certain architectural model / patterncertain architectural model / pattern
System System Architecture Architecture
Diagram – Diagram – ExampleExample
Example of Multi-Tier Example of Multi-Tier Software ArchitectureSoftware Architecture
6
Client-Server Client-Server ArchitectureArchitecture
The Classical Client-Server ModelThe Classical Client-Server Model
Client-Server Client-Server ArchitectureArchitecture
The client-server model consists of:The client-server model consists of: ServerServer – a single machine / application – a single machine / application
that provides services to multiple clientsthat provides services to multiple clients
Could be IIS based Web serverCould be IIS based Web server
Could be WCF based serviceCould be WCF based service
Could be a services in the cloudCould be a services in the cloud
Clients Clients –software applications that –software applications that provide UI (front-end) to access the provide UI (front-end) to access the services at the serverservices at the server
Could be WPF, HTML5, Silverlight, Could be WPF, HTML5, Silverlight, ASP.NET, …ASP.NET, …
8
The Client-Server ModelThe Client-Server Model
9
ServerServer
DesktopDesktopClientClient
MobileMobileClientClient
ClientClientMachineMachine
network connection
network connection
network connectionnetwork connection
network connection
network connection
Client-Server Model – Client-Server Model – ExamplesExamples
Web server (IIS) – Web browser (Firefox)Web server (IIS) – Web browser (Firefox) FTP server (ftpd) – FTP client (FileZilla)FTP server (ftpd) – FTP client (FileZilla) EMail server (qmail) – email client (Outlook)EMail server (qmail) – email client (Outlook) SQL Server – SQL Server Management StudioSQL Server – SQL Server Management Studio BitTorrent Tracker – Torrent client (BitTorrent Tracker – Torrent client (μμTorrent)Torrent) DNS server (bind) – DNS client (resolver)DNS server (bind) – DNS client (resolver) DHCP server (wireless router firmware) – DHCP server (wireless router firmware) –
DHCP client (mobile phone /Android DHCP DHCP client (mobile phone /Android DHCP client/)client/)
SMB server (Windows) – SMB client SMB server (Windows) – SMB client (Windows)(Windows)
10
3-Tier / Multi-Tier 3-Tier / Multi-Tier ArchitecturesArchitectures
Classical Layered Structure of Classical Layered Structure of Software SystemsSoftware Systems
The 3-Tier ArchitectureThe 3-Tier Architecture The The 3-tier architecture 3-tier architecture consists of the consists of the
following tiers (layers):following tiers (layers): Front-endFront-end (client layer) (client layer)
ClientClient software – provides the UI of the software – provides the UI of the systemsystem
Middle tier Middle tier (business layer)(business layer) Server software – provides the core system Server software – provides the core system
logiclogic
Implements the business processes / servicesImplements the business processes / services
Back-endBack-end (data layer) (data layer) Manages the data of the system (database / Manages the data of the system (database /
cloud)cloud)12
The 3-Tier Architecture The 3-Tier Architecture ModelModel
13
BusinessBusinessLogicLogic DesktopDesktop
ClientClient
MobileMobileClientClient
ClientClientMachineMachine
networknetwork
networknetwork
network
networkDatabaseDatabase
Data TierData Tier(Back-End)(Back-End)
Middle TierMiddle Tier(Business Tier)(Business Tier)
Client Tier (Front-End)Client Tier (Front-End)
Typical Layers of the Typical Layers of the Middle TierMiddle Tier
The middle tier usually has parts The middle tier usually has parts related to the front-end, business related to the front-end, business logic and back-end:logic and back-end:
14
Presentation LogicPresentation LogicImplements the UI of the application (HTML5, Silverlight, WPF, …)Implements the UI of the application (HTML5, Silverlight, WPF, …)
Business LogicBusiness LogicImplements the core processes / services of the applicationImplements the core processes / services of the application
Data Access LogicData Access LogicImplements the data access functionality (usually ORM framework)Implements the data access functionality (usually ORM framework)
Multi-Tier ArchitectureMulti-Tier Architecture
15
DBDB
ORMORM
WCFWCF
ASPASP.NET.NET
HTMLHTML
MVC (Model-MVC (Model-View-Controller)View-Controller)
What is MVC and How It Works?What is MVC and How It Works?
Model-View-Controller Model-View-Controller (MVC)(MVC)
Model-View-Controller (MVC)Model-View-Controller (MVC) architecture architecture Separates the business logic from Separates the business logic from
application data and presentationapplication data and presentation ModelModel
Keeps the application state (data)Keeps the application state (data) ViewView
Displays the data to the user (shows UI)Displays the data to the user (shows UI) ControllerController
Handles the interaction with the userHandles the interaction with the user17
MVC Architecture MVC Architecture BlueprintBlueprint
18
MVC-Based MVC-Based FrameworksFrameworks
.NET.NET ASP.NET MVC, MonoRailASP.NET MVC, MonoRail
JavaJava JavaServer Faces (JSF), Struts, Spring Web JavaServer Faces (JSF), Struts, Spring Web
MVC, Tapestry, JBoss Seam, SwingMVC, Tapestry, JBoss Seam, Swing PHPPHP
CakePHP, Symfony, ZendCakePHP, Symfony, Zend, , JoomlaJoomla, , Yii, Yii, MojaviMojavi
PythonPython Django, Zope Application Server, Django, Zope Application Server,
TurboGearsTurboGears
Ruby on RailsRuby on Rails19
MVC and Multi-Tier MVC and Multi-Tier ArchitectureArchitecture
MVC does not MVC does not replace the replace the multi-tier multi-tier architecturearchitecture Both are usually Both are usually
used togetherused together
Typical multi-Typical multi-tier tier architecture architecture can use MVCcan use MVC To separate To separate
logic, data and logic, data and presentationpresentation
20
Model (Data)Model (Data)
Data Access Data Access LogicLogic
ViewsViews(Presentati(Presentati
on)on)
ControllersControllers(Business (Business
Logic)Logic)
MVP (Model-View-MVP (Model-View-Presenter)Presenter)What is MVP Architecture and How it What is MVP Architecture and How it
Works?Works?
Model-View-Presenter Model-View-Presenter (MVP)(MVP)
Model-View-Presenter (MVP)Model-View-Presenter (MVP) is UI is UI design pattern similar to MVCdesign pattern similar to MVC ModelModel
Keeps application data (state)Keeps application data (state)
ViewView Presentation – displays the UI and Presentation – displays the UI and
handles UI events (keyboard, mouse, handles UI events (keyboard, mouse, etc.)etc.)
PresenterPresenter Presentation logic (prepares data taken Presentation logic (prepares data taken
from the model to be displayed in from the model to be displayed in certain format)certain format) 22
Presentation-Presentation-Abstraction-Control Abstraction-Control
(PAC)(PAC)What is PAC and How It Works?What is PAC and How It Works?
Presentation-Presentation-Abstraction-Control Abstraction-Control
(PAC)(PAC) Presentation-Abstraction-Control (PAC) Presentation-Abstraction-Control (PAC)
interaction-oriented architectural patterninteraction-oriented architectural pattern Similar to MVC but is hierarchical (like Similar to MVC but is hierarchical (like
HMVC)HMVC) PresentationPresentation
Prepares data for the UI (similar to Prepares data for the UI (similar to ViewView))
AbstractionAbstraction Retrieves and processes data (similar to Retrieves and processes data (similar to
ModelModel))
ControlControl Flow-control and communication (similar to Flow-control and communication (similar to
ControllerController))24
Presentation-Presentation-Abstraction-Control Abstraction-Control
(PAC) – Hierarchy(PAC) – Hierarchy
25
MVVM MVVM ((Model-Model-View-View-
ViewModelViewModel))What is MVVM What is MVVM
and How It and How It Works?Works?
Model-View-Model-View-ViewModelViewModel (MVVM)(MVVM)
Model-View-ViewModelModel-View-ViewModel (MVVM) (MVVM) is is architectural pattern for modern UI architectural pattern for modern UI developmentdevelopment
Invented by Microsoft for use in WPF and Invented by Microsoft for use in WPF and SilverlightSilverlight
Based on Based on MVCMVC, , MVPMVP and Martin Fowler's and Martin Fowler's Presentation Model Presentation Model patternpattern
Officially published in the Prism project Officially published in the Prism project (Composite Application Guidance for WPF (Composite Application Guidance for WPF and Silverlight)and Silverlight)
Separates the "Separates the "view layerview layer" (state and " (state and behavior) from the rest of the applicationbehavior) from the rest of the application 27
MVVM StructureMVVM Structure ModelModel
Keeps the application data / state Keeps the application data / state representationrepresentation
E.g. data access layer or ORM frameworkE.g. data access layer or ORM framework ViewView
UI elements of the applicationUI elements of the application
Windows, forms, controls, fields, buttons, Windows, forms, controls, fields, buttons, etc.etc.
ViewModelViewModel Data binder and converter that changes the Data binder and converter that changes the
ModelModel information into information into ViewView information information
Exposes Exposes commandscommands for binding in the for binding in the ViewsViews28
MVVM in WPF / MVVM in WPF / SilverlightSilverlight
ViewView – implemented by XAML code + – implemented by XAML code + code behind C# classcode behind C# class
ModelModel – implemented by WCF – implemented by WCF services / ORM framework / data services / ORM framework / data access classesaccess classes
ViewModelViewModel – implemented by C# class – implemented by C# class and keeps data (properties), and keeps data (properties), commands (code), notificationscommands (code), notifications
29
MVVM ArchitectureMVVM Architecture MVVM is typically used in XAML MVVM is typically used in XAML
applications (WPF, Silverlight, WP7) applications (WPF, Silverlight, WP7) and supports unit testingand supports unit testing
30
MVP vs. MVVM PatternsMVP vs. MVVM Patterns
31
MVVM is like MVP but leverages the platform's MVVM is like MVP but leverages the platform's build-in bi-directional build-in bi-directional data binding data binding mechanismsmechanisms
IoC (Inversion of IoC (Inversion of Control) and DI Control) and DI (Dependency (Dependency
Injection)Injection)Architectural Principals or Design Architectural Principals or Design Patterns?Patterns?
Inversion of Control Inversion of Control (IoC)(IoC)
Inversion of Control (IoC)Inversion of Control (IoC) is an abstract is an abstract principle in software design in whichprinciple in software design in which The flow of control of a system is inverted The flow of control of a system is inverted
compared to procedural programmingcompared to procedural programming
The main control of the program is The main control of the program is inverted, moved away from you to the inverted, moved away from you to the frameworkframework
Basic IoC principle:Basic IoC principle:
Implementations typically rely on Implementations typically rely on callbackscallbacks
33
Don't call us, we'll call you!Don't call us, we'll call you!
Procedural Flow Control – Procedural Flow Control – ExampleExample
34
private void DoSomeTransactionalWork(IDbSesion)private void DoSomeTransactionalWork(IDbSesion){{ … …}}
IDbSession session = new DbSession();IDbSession session = new DbSession();session.BeginTransaction(); session.BeginTransaction(); trytry{{ DoSomeTransactionalWork(session);DoSomeTransactionalWork(session); session.CommitTransaction();session.CommitTransaction();}}catch (Exception)catch (Exception){{ session.RollbackTransaction();session.RollbackTransaction(); throw;throw;}}
Step by stepStep by stepexecutionexecution
Inverted Flow Control – Inverted Flow Control – ExampleExample
35
private static void ExecuteInTransaction(private static void ExecuteInTransaction( Action<IDbSession> doSomeTransactionalWork)Action<IDbSession> doSomeTransactionalWork){{ IDbSession session = new DbSession();IDbSession session = new DbSession(); session.BeginTransaction();session.BeginTransaction(); trytry {{ doSomeTransactionalWork(session);doSomeTransactionalWork(session); session.CommitTransaction();session.CommitTransaction(); }} catch (Exception)catch (Exception) {{ session.RollbackTransaction();session.RollbackTransaction(); throw;throw; }}}}
ExecuteInTransaction(DoSomeTransactionalWork);ExecuteInTransaction(DoSomeTransactionalWork);
Inverted flow controlInverted flow control
Dependency Inversion Dependency Inversion PrinciplePrinciple
Dependency inversion principleDependency inversion principle Decouples high-level components Decouples high-level components
from low-level componentsfrom low-level components
To allow reuse with different low-To allow reuse with different low-level component implementationslevel component implementations
Design patterns implementing the Design patterns implementing the dependency inversion principle:dependency inversion principle: Dependency InjectionDependency Injection
Service LocatorService Locator
36
Highly Dependent Highly Dependent ComponentsComponents
Example of highly dependent Example of highly dependent components:components:
The The LogsDAOLogsDAO class is highly-coupled class is highly-coupled (dependent) to (dependent) to DbSessionDbSession class class
37
public class LogsDAOpublic class LogsDAO{{ private void AppendToLogs(string message)private void AppendToLogs(string message) {{ DbSession session = new DbSession();DbSession session = new DbSession(); session.ExecuteSqlWithParams("INSERT INTO " + session.ExecuteSqlWithParams("INSERT INTO " + "Logs(MsgDate, MsgText) VALUES({0},{1})","Logs(MsgDate, MsgText) VALUES({0},{1})", DateTime.Now, message);DateTime.Now, message); }}}}
Decoupled ComponentsDecoupled Components
38
public class LogsDAOpublic class LogsDAO{{ private IDbSession session;private IDbSession session;
public LogsDAO(IDbSession session)public LogsDAO(IDbSession session) {{ this.session = session;this.session = session; }}
private void AppendToLogs(string message)private void AppendToLogs(string message) {{ session.ExecuteSqlWithParams("INSERT INTO " + session.ExecuteSqlWithParams("INSERT INTO " + "Logs(MsgDate, MsgText) VALUES({0},{1})","Logs(MsgDate, MsgText) VALUES({0},{1})", DateTime.Now, message);DateTime.Now, message); }}}}
The The LogsDAOLogsDAO and and DbSessionDbSession are now are now decoupleddecoupled
Decoupling Decoupling ComponentsComponents
39
LogsDAOLogsDAO
DbSessioDbSessionn
depends ondepends on
LogsDALogsDAOO
IDbSessionIDbSession
depend ondepend on
DbSessiDbSessionon
Highly-Highly-coupled coupled componentscomponents::
Decoupled Decoupled componentscomponents::
Dependency Injection Dependency Injection (DI)(DI)
Dependency Injection (DI)Dependency Injection (DI) is the main is the main method to implement Inversion of Control method to implement Inversion of Control (IoC) pattern(IoC) pattern DI and IoC are considered the same conceptDI and IoC are considered the same concept DI separates behavior from dependency DI separates behavior from dependency
resolution and thus decouples highly resolution and thus decouples highly dependent componentsdependent components
Dependency injection means passing or Dependency injection means passing or setting of dependencies into a software setting of dependencies into a software componentcomponent
Instead of components having to request Instead of components having to request dependencies, they are passed (injected) dependencies, they are passed (injected) into the componentinto the component
40
Types of InjectionTypes of Injection Dependency Injection (DI) usually runs with Dependency Injection (DI) usually runs with
IoC ContainerIoC Container (also called (also called DI ContainerDI Container)) Types of dependency injection:Types of dependency injection:
Constructor injectionConstructor injection – a dependency is – a dependency is passed to the constructor as a parameterpassed to the constructor as a parameter
Setter injectionSetter injection – a dependency is injected – a dependency is injected into the dependent object through a into the dependent object through a property setterproperty setter
Interface injectionInterface injection – an interface is used to – an interface is used to inject a dependency into the dependent inject a dependency into the dependent objectobject
IoC containers can inject dependencies IoC containers can inject dependencies automatically at run-timeautomatically at run-time
41
IoC Container – IoC Container – ExampleExample
IoC containers have two main IoC containers have two main functionsfunctions Register injectable classesRegister injectable classes
Can be done declaratively (with XML or Can be done declaratively (with XML or attributes) or programmatically (in C# attributes) or programmatically (in C# code)code)
Resolve already registered classesResolve already registered classes
Done in C# code at runtimeDone in C# code at runtime
Dependency injection could be done Dependency injection could be done automatically with no codeautomatically with no code
E.g. E.g. autowire autowire in Spring frameworkin Spring framework 42
IoC Container – IoC Container – Example (2)Example (2)
43
Consider the following code:Consider the following code:
We want to use IoC container to resolve We want to use IoC container to resolve the dependency between our code and the dependency between our code and the loggerthe logger
public interface ILoggerpublic interface ILogger{{ void LogMessage(string msg);void LogMessage(string msg);}}
public class ConsoleLogger : ILoggerpublic class ConsoleLogger : ILogger{{ public void LogMessage(string msg)public void LogMessage(string msg) {{ Console.WriteLine(msg);Console.WriteLine(msg); }}}}
IoC Container – IoC Container – Example (3)Example (3)
Consider the IoC container Consider the IoC container provides the following methods:provides the following methods:
Registering the logger:Registering the logger:
Using the registered logger:Using the registered logger:
44
IoC.Register<ILogger>(new ConsoleLogger());IoC.Register<ILogger>(new ConsoleLogger());
ILogger logger = IoC.Resolve<ILogger>();ILogger logger = IoC.Resolve<ILogger>();logger.LogMessage("Hello, world!");logger.LogMessage("Hello, world!");
IoC Containers for .NETIoC Containers for .NET Microsoft ObjectBuilder; Microsoft UnityMicrosoft ObjectBuilder; Microsoft Unity
Open-source projects at CodePlexOpen-source projects at CodePlex
Part of Patterns & Practices Enterprise Part of Patterns & Practices Enterprise LibraryLibrary
Spring.NET – Spring.NET – www.springframework.net .NET port of the famous Spring .NET port of the famous Spring
framework from the Java world framework from the Java world (currently owned by VMware)(currently owned by VMware)
Castle Windsor –Castle Windsor –www.castleproject.org Open-source IoC container, part of the Open-source IoC container, part of the
Castle projectCastle project45
Microsoft PrismMicrosoft Prism Patterns and Practices: PrismPatterns and Practices: Prism
Patterns For Building Composite Patterns For Building Composite Applications With WPF and SilverlightApplications With WPF and Silverlight
Composite applications – consists of Composite applications – consists of loosely coupled modules discoverable at loosely coupled modules discoverable at runtimeruntime
Prism componentsPrism components Prism LibraryPrism Library Stock Trader Reference Implementation Stock Trader Reference Implementation MVVM Reference ImplementationMVVM Reference Implementation QuickStartsQuickStarts
46
Managed Extensibility Managed Extensibility Framework (MEF)Framework (MEF)
Managed Extensibility Framework Managed Extensibility Framework (MEF)(MEF) Simplifies the design of extensible Simplifies the design of extensible
applications and componentsapplications and components
Official part of .NET Framework 4Official part of .NET Framework 4
Allows developers to discover and use Allows developers to discover and use extensions with no configuration at extensions with no configuration at runtimeruntime
lets extension developers easily lets extension developers easily encapsulate code and avoid fragile encapsulate code and avoid fragile hard dependencieshard dependencies 47
SOA (Service-SOA (Service-Oriented Oriented
Architecture)Architecture)SOA and Cloud ComputingSOA and Cloud Computing
What is SOA?What is SOA?
Service-Oriented Architecture (SOA)Service-Oriented Architecture (SOA) is a concept for development of is a concept for development of software systemssoftware systems
Using reusable building blocks Using reusable building blocks (components) called "services"(components) called "services"
Services in SOA are:Services in SOA are:
Autonomous, stateless business Autonomous, stateless business functionsfunctions
Accept requests and return responsesAccept requests and return responses
Use well-defined, standard interfaceUse well-defined, standard interface
SOA ServicesSOA Services AutonomousAutonomous
Each service operates autonomouslyEach service operates autonomously
Without any awareness that other Without any awareness that other services existservices exist
StatelessaStatelessa
Have no memory, do not remember Have no memory, do not remember statestate
Easy to scaleEasy to scale
Request-response modelRequest-response model
Client asks, server returns answerClient asks, server returns answer
SOA Services (2)SOA Services (2) Communication through standard Communication through standard
protocolsprotocols
XML, SOAP, JSON, RSS, ATOM, ...XML, SOAP, JSON, RSS, ATOM, ...
HTTP, FTP, SMTP, RPC, ...HTTP, FTP, SMTP, RPC, ...
Not dependent on OS, platforms, Not dependent on OS, platforms, programming languagesprogramming languages
DiscoverableDiscoverable
Service registriesService registries
Could be hosted "in the cloud" (e.g. in Could be hosted "in the cloud" (e.g. in Azure)Azure)
What is Cloud What is Cloud Computing?Computing?
Cloud computing Cloud computing is a modern approach in is a modern approach in the IT infrastructure that providesthe IT infrastructure that provides:: Software applications, services, hardware and Software applications, services, hardware and
system resourcessystem resources Hosts the applications and user data in remote Hosts the applications and user data in remote
servers called "the cloud"servers called "the cloud"
Cloud computing modelsCloud computing models:: IaaS – infrastructure as a service (virtual IaaS – infrastructure as a service (virtual
servers)servers) PaaS – platform as a service (full stack of PaaS – platform as a service (full stack of
technologies for UI , application logic, data technologies for UI , application logic, data storage)storage)
SaaS – software as a service (e.g. Google Docs)SaaS – software as a service (e.g. Google Docs)52
Loose CouplingLoose Coupling Loose coupling Loose coupling is the main concept of is the main concept of
SOASOA Loosely coupled components:Loosely coupled components:
Exhibits single functionExhibits single function Independent of other functionsIndependent of other functions Through a well-defined interfaceThrough a well-defined interface
Loose coupling programming evolves:Loose coupling programming evolves: Structural programmingStructural programming Object-oriented programmingObject-oriented programming Service-oriented architecture (SOA)Service-oriented architecture (SOA)
SOA Design PatternsSOA Design Patterns SOA Patterns – www.soapatterns.org
Inventory Foundation, Logical Layer, Implementation, Governance Patterns
Service Foundational, Implementation, Security, Contract, Governance, Messaging Patterns
Legacy Encapsulation Patterns
Capability Composition Patterns
Composition Implementation Patterns
Transformation Patterns
Common Compound Design Patterns 54
Architectural PatternsArchitectural Patterns
Questions?Questions?
top related