architecture and design patterns

29
Architecture and Architecture and design patterns design patterns Jonathan Einav Jonathan Einav

Upload: karan

Post on 03-Feb-2016

40 views

Category:

Documents


0 download

DESCRIPTION

Architecture and design patterns. Jonathan Einav. Lecture Objectives. Open a window to the architecture and design patterns world, explain why are they needed and where did they came from, and give some examples and real world tastes of chosen DP and architectures - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Architecture and design patterns

Architecture and design Architecture and design patternspatterns

Jonathan EinavJonathan Einav

Page 2: Architecture and design patterns

Lecture ObjectivesLecture Objectives

Open a window to the architecture and Open a window to the architecture and design patterns world, explain why are design patterns world, explain why are they needed and where did they came they needed and where did they came from, and give some examples and real from, and give some examples and real world tastes of chosen DP and world tastes of chosen DP and architecturesarchitectures

not a programming language oriented not a programming language oriented lecture, we will mainly discuss the lecture, we will mainly discuss the paradigms and uses with examples in paradigms and uses with examples in various programming languages. various programming languages.

Page 3: Architecture and design patterns

Programming paradigms EvolutionProgramming paradigms Evolution

Block ProgrammingBlock Programming

Procedural programmingProcedural programming

Object OrientedObject Oriented

Component OrientedComponent Oriented

SOA (?)SOA (?)

Page 4: Architecture and design patterns

What are design patterns?What are design patterns?

The Beginning - “Gang of four” (Gama et al The Beginning - “Gang of four” (Gama et al 1995)1995)

What's the difference between an architecture What's the difference between an architecture and a Design patterns?and a Design patterns?

Patterns sub types:Patterns sub types: Creational Creational StructuralStructural BehavioralBehavioral

Page 5: Architecture and design patterns

Observer design patternsObserver design patterns

Behavioral PatternBehavioral Patternone-to-many dependency model, so that when one one-to-many dependency model, so that when one object changes state, all its dependents are notified and object changes state, all its dependents are notified and updated automatically without coupling the notifying updated automatically without coupling the notifying object to the objects that are notified. object to the objects that are notified.

Example:Example:Button expose a clicked event that encapsulate click Button expose a clicked event that encapsulate click state, thus publish himself as an observable. Clients that state, thus publish himself as an observable. Clients that are interested in this event register to it, thus becomes are interested in this event register to it, thus becomes observers.observers.Observer and observable are bonded in a contract and Observer and observable are bonded in a contract and can be completely loosely coupled from one another.can be completely loosely coupled from one another.

Page 6: Architecture and design patterns

Singleton design patternSingleton design pattern

Creational patternCreational patternensure that a class has only one instance, and to provide a global ensure that a class has only one instance, and to provide a global point of access to it point of access to it

Example:Example:Class SomeClassClass SomeClass{{

static SomeClass singleTonInstance = null;static SomeClass singleTonInstance = null;

static SomeClass GetInstance()static SomeClass GetInstance(){{

if(singleTonInstance == null)if(singleTonInstance == null) singleTonInstance = new SomeClass()singleTonInstance = new SomeClass()

return singleTonInstance;return singleTonInstance;}}

}}

Page 7: Architecture and design patterns

Factory design patterns (abstract\Factory design patterns (abstract\method\Lightweight)method\Lightweight)

Creational patternCreational pattern

Can be given to client (abstract), pass Can be given to client (abstract), pass construction parameters or read creation construction parameters or read creation types from configuration or system types from configuration or system environmentenvironment

Can use object pool (Lightweight)Can use object pool (Lightweight)

Page 8: Architecture and design patterns

Factory design pattern - exampleFactory design pattern - exampleabstract class GUIFactory { abstract class GUIFactory {

public static GUIFactory getFactory() { public static GUIFactory getFactory() { int sys = readFromConfigFile("OS_TYPE"); int sys = readFromConfigFile("OS_TYPE"); return sys == 0 ? new WinFactory() : new OSXFactory(); return sys == 0 ? new WinFactory() : new OSXFactory();

} } public abstract Button createButton(); public abstract Button createButton();

}}class WinFactory:GUIFactory {class WinFactory:GUIFactory {

public override Button createButton() { public override Button createButton() { return new WinButton(); return new WinButton();

} } } } class MacFactory:GUIFactory { class MacFactory:GUIFactory {

public override Button createButton(){ public override Button createButton(){ return new MacButton(); return new MacButton();

} } } } abstract class Button { abstract class Button {

public string caption; public string caption; public abstract void paint(); public abstract void paint();

} }

Page 9: Architecture and design patterns

class WinButton:Button class WinButton:Button { {

public override void paint() public override void paint() { // paint a button with Win API…} { // paint a button with Win API…}

} } class MacButton:Button class MacButton:Button { {

public override void paint() public override void paint() { // paint a button Mac style… }{ // paint a button Mac style… }

}}class Application class Application { {

static void Main(string[] args) static void Main(string[] args) { {

GUIFactory aFactory = GUIFactory.getFactory();GUIFactory aFactory = GUIFactory.getFactory();Button aButton = aFactory.createButton(); Button aButton = aFactory.createButton(); aButton.caption = "Play"; aButton.paint(); aButton.caption = "Play"; aButton.paint();

}}} }

Factory design pattern - exampleFactory design pattern - example

Page 10: Architecture and design patterns

Façade design patternFaçade design pattern

Structural PatternStructural Pattern

Provide a unified interface to a set of interfaces Provide a unified interface to a set of interfaces in a subsystem without damaging the genric in a subsystem without damaging the genric form of the sub system. form of the sub system.

Page 11: Architecture and design patterns

Decorator design patternDecorator design pattern

Structural PatternStructural Pattern

Avoid excessive sub-classing and gain run Avoid excessive sub-classing and gain run time flexibilitytime flexibility

Example: Example:

Java.IO packageJava.IO packageBufferedReader br = BufferedReader br = new new BufferedReader(BufferedReader(

new new InputStreamReader(InputStreamReader(                    

new new FileInputStream(inFile)));FileInputStream(inFile)));

All derives from abstract io.Reader All derives from abstract io.Reader

Page 12: Architecture and design patterns

Strategy design patternStrategy design patternBehavioral PatternBehavioral Patterndefines a family of interchangeable encapsulated algorithms that defines a family of interchangeable encapsulated algorithms that receives the same input type and provides the same output type in receives the same input type and provides the same output type in different manners that can be determined in run-time. different manners that can be determined in run-time.

static void Main(static void Main({{

SortedList studentRecords = new SortedList();SortedList studentRecords = new SortedList();studentRecords.Add("Samual");studentRecords.Add("Samual");studentRecords.Add("Jimmy");studentRecords.Add("Jimmy");studentRecords.Add("Sandra");studentRecords.Add("Sandra");        studentRecords.SetSortStrategy(new QuickSort());studentRecords.SetSortStrategy(new QuickSort());studentRecords.Sort();studentRecords.Sort();studentRecords.SetSortStrategy(new ShellSort());studentRecords.SetSortStrategy(new ShellSort());studentRecords.Sort();  studentRecords.Sort();  

}}

Page 13: Architecture and design patterns

Strategy design pattern - exampleStrategy design pattern - example

abstract class SortStrategyabstract class SortStrategy{{

public abstract void Sort(ArrayList list)public abstract void Sort(ArrayList list)}}class QuickSort : SortStrategyclass QuickSort : SortStrategy{{

public override void Sort(ArrayList list)public override void Sort(ArrayList list){{      list.Sort(); // Default is Quicksort             list.Sort(); // Default is Quicksort       }}

}}class ShellSort : SortStrategyclass ShellSort : SortStrategy{{

public override void Sort(ArrayList list)public override void Sort(ArrayList list){ {       //list.ShellSort(); not-implemented            //list.ShellSort(); not-implemented      }  }  

}}

Page 14: Architecture and design patterns

class SortedListclass SortedList{{

private ArrayList list = new ArrayList();private ArrayList list = new ArrayList();private SortStrategy sortstrategy;private SortStrategy sortstrategy;

public void SetSortStrategy(SortStrategy sortstrategy)public void SetSortStrategy(SortStrategy sortstrategy){{      this.sortstrategy = sortstrategy;      this.sortstrategy = sortstrategy;}}

public void Add(string name)public void Add(string name){      {      

list.Add(name);list.Add(name);}}        public void Sort()public void Sort(){   {      sortstrategy.Sort(list); sortstrategy.Sort(list); 

            }}}}

Strategy design pattern - exampleStrategy design pattern - example

Page 15: Architecture and design patterns

Consumer/ProducerConsumer/Producer

Concurrency PatternConcurrency Pattern

This design pattern coordinates the This design pattern coordinates the concurrent production and consumption of concurrent production and consumption of information among producer and information among producer and consumer objects that are working on consumer objects that are working on different threads.different threads.

This pattern is used with some type of This pattern is used with some type of semaphoresemaphore

Page 16: Architecture and design patterns

Consumer/Producer - exampleConsumer/Producer - examplestatic AutoResetEvent eventProducerDone = new AutoResetEvent(false);static AutoResetEvent eventProducerDone = new AutoResetEvent(false);static AutoResetEvent eventConsumerDone = newstatic AutoResetEvent eventConsumerDone = new AutoResetEvent(false);AutoResetEvent(false);static int currentNum = 0;static int currentNum = 0;

static void produce(object stateInfo)static void produce(object stateInfo){{ eventProducerDone.Set();eventProducerDone.Set(); while (true)while (true) {{ //wait for the consumer//wait for the consumer eventConsumerDone.WaitOne();eventConsumerDone.WaitOne(); currentNum++;currentNum++; eventProducerDone.Set();eventProducerDone.Set(); }}}}

Page 17: Architecture and design patterns

static void Main(string[] args)static void Main(string[] args){{ ThreadPool.QueueUserWorkItem(new ThreadPool.QueueUserWorkItem(new

WaitCallback(produce));WaitCallback(produce)); for (int i = 0; i < 20; i++)for (int i = 0; i < 20; i++) {{ eventProducerDone.WaitOne();eventProducerDone.WaitOne(); System.Diagnostics.Debug.WriteLine(currentNum);System.Diagnostics.Debug.WriteLine(currentNum); eventConsumerDone.Set();eventConsumerDone.Set(); }}}}

Consumer/Producer - exampleConsumer/Producer - example

Page 18: Architecture and design patterns

Model View ControllerModel View Controller

The Model-View-Controller (MVC) pattern The Model-View-Controller (MVC) pattern separates the modeling of the domain, the separates the modeling of the domain, the presentation, and the actions based on presentation, and the actions based on user input into three separate classesuser input into three separate classesThe controller changes the model The controller changes the model The View Listens to Model The View Listens to Model Changed events and Changed events and update itselfupdate itselfRecursive MVCRecursive MVC

Page 19: Architecture and design patterns

N tier ArchitectureN tier ArchitectureThe n tier architecture is based on the The n tier architecture is based on the concept of separating a system to concept of separating a system to different layers (usually 3) Each layer different layers (usually 3) Each layer interacts with only the layer directly interacts with only the layer directly below, and has specific function that it below, and has specific function that it is responsible for.is responsible for.

Classic for IT systemsClassic for IT systems

Page 20: Architecture and design patterns

N tier ArchitectureN tier Architecture

3 Tier architecture: 3 Tier architecture: Presentation LayerPresentation Layer

Presentation Layer is the layer responsible for displaying user interface.Presentation Layer is the layer responsible for displaying user interface. Business TierBusiness Tier

Business Tier is the layer responsible for accessing the data tier to Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer. processing the data retrieved and sent to the presentation layer. BLL and DALBLL and DALOften this layer is divided into two sub layers: the Business Logic Layer Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL. objects. DAL is responsible for accessing data and forwarding it to BLL.

Data TierData TierData tier is the database or the source of the data itself.Data tier is the database or the source of the data itself.

Common mistakes – tightly coupling layers in technology and writing Common mistakes – tightly coupling layers in technology and writing business logic in presentation tierbusiness logic in presentation tier

Page 21: Architecture and design patterns

Hexagon Architecture Hexagon Architecture

Allow an application to equally be driven Allow an application to equally be driven by users, programs, automated test or by users, programs, automated test or batch scripts.batch scripts.

Page 22: Architecture and design patterns

SOASOA

SOA is an architectural style whose goal is SOA is an architectural style whose goal is to achieve loose coupling among to achieve loose coupling among interacting software agents. interacting software agents. A service is a unit of work done by a A service is a unit of work done by a service provider to achieve desired end service provider to achieve desired end results for a service consumer results for a service consumer in SOA, services are the mechanism by in SOA, services are the mechanism by which needs and capabilities are brought which needs and capabilities are brought together.together.

Page 23: Architecture and design patterns

SOA - PrinciplesSOA - Principles

Visibility – the ability for a service Visibility – the ability for a service consumer to “see” a service provider consumer to “see” a service provider (Awareness, willingness and Reachability)(Awareness, willingness and Reachability)Interaction - the activity of using a Interaction - the activity of using a capability. (usually message exchange - capability. (usually message exchange - by contracts, constraints and policies, for by contracts, constraints and policies, for example Web Service Description example Web Service Description Language)Language)Effect – the result of an interactionEffect – the result of an interaction

Page 24: Architecture and design patterns

SOA - exampleSOA - example

Page 25: Architecture and design patterns

Component Manager and EXE Component Manager and EXE Runner paradigmRunner paradigm

Why should the GUI client have the EXE main Why should the GUI client have the EXE main thread?thread?Why shouldn’t we have a visual and easy to use Why shouldn’t we have a visual and easy to use interface for configuring and\or adding\removing interface for configuring and\or adding\removing physical components?physical components?Solution: Solution: Component Manager – drag and drop assemblies and Component Manager – drag and drop assemblies and

connect functionality using events and delegate connect functionality using events and delegate signatures, eventually compile an XML file that will signatures, eventually compile an XML file that will represent all assemblies and connectionsrepresent all assemblies and connections

EXE Runner – Run the XML file with the EXE main EXE Runner – Run the XML file with the EXE main thread loading the application assemblies and thread loading the application assemblies and connecting relations in run-timeconnecting relations in run-time

Page 26: Architecture and design patterns

Components Vs namespaces Vs Components Vs namespaces Vs ClassesClasses

Classes separation OOP conceptsClasses separation OOP concepts

Namespace separation -Logical domain Namespace separation -Logical domain considerations (functional)considerations (functional)

Assembly separation - Physical domain Assembly separation - Physical domain considerations (maintenance, usability)considerations (maintenance, usability)

Page 27: Architecture and design patterns

Thin, rich and smart clientsThin, rich and smart clients

Thin client – webThin client – webRich client – full blown applicationRich client – full blown applicationSmart client – Smart client – components on components on demand in demand in click-once click-once deployment and deployment and update approachupdate approach

Page 28: Architecture and design patterns

Code and configuration separationCode and configuration separation

Hard Code AS LITTLE AS POSSIBLEHard Code AS LITTLE AS POSSIBLEPros – Extensibility, less bugs (less code Pros – Extensibility, less bugs (less code changes), different suite support under the changes), different suite support under the same code base with less administrative same code base with less administrative overhead (documentation, deployment, overhead (documentation, deployment, QA etc.)QA etc.)Cons – performance, coding overheadCons – performance, coding overheadEL 2.0 Configuration application blockEL 2.0 Configuration application blockNear future - XAML of AvalonNear future - XAML of Avalon

Page 29: Architecture and design patterns

About meAbout me

B.A with honors in CS. B.A with honors in CS. Assumed different industrial positions Assumed different industrial positions such as R&D Manager, chief Architect and such as R&D Manager, chief Architect and Projects manager in Various industry Projects manager in Various industry domains such as the Medical , Education domains such as the Medical , Education and the Security domains. and the Security domains. Consultant to various companies in Consultant to various companies in software management, architecture and software management, architecture and MS .NET issuesMS .NET issuesMember of the Microsoft .NET Fight Club.Member of the Microsoft .NET Fight Club.