SlideShare a Scribd company logo
Mohammad Shaker 
mohammadshaker.com 
@ZGTRShaker 
2011, 2012, 2013, 2014 
C# Advanced 
L07–Design Patterns
Gang of Four(GoF) Gamma, Helm, Johnson, Vlissides
Gamma et al, Design Patterns: Elements of Reusable Object-Oriented SoftwareAddison Wesley, 1995
Scope 
•Patterns solve software structural problems like: 
–Abstraction, 
–Encapsulation 
–Information hiding 
–Separation of concerns 
–Coupling and cohesion 
–Separation of interface and implementation 
–Single point of reference 
–Divide and conquer 
•Patterns also solve non-functional problems like: 
–Changeability 
–Interoperability 
–Efficiency 
–Reliability 
–Testability 
–Reusability
Types of Pattern 
•There are 3 types of pattern: 
–Creational: address problems of creating an object in a flexible way. Separate creation, from operation/use. 
–Structural: address problems of using O-O constructs like inheritance to organize classes and objects 
–Behavioral: address problems of assigning responsibilities to classes. Suggest both static relationships and patterns of communication
Classification of Design Patterns 
Purpose 
Creational 
Structural 
Behavioral 
Factory Method 
Adapter 
Interpreter 
Abstract Factory 
Bridge 
Template Method 
Builder 
Composite 
Chain of Responsibility 
Prototype 
Decorator 
Command 
Singleton 
Façade 
Iterator 
Flyweight 
Mediator 
Proxy 
Memento 
Observer 
State 
Strategy 
Visitor
Patterns
Patterns 
•Singleton 
–Ensure a class only has one instance 
–Provide a global point of access to it 
•Abstract Factory 
–Provide an interface for creating families of related or dependent objects without specifying their concrete classes 
•Factory Method 
–Define an interface for creating an object but let subclasses decide which class to instantiate 
–Lets a class defer instantiation to subclasses 
•Prototype 
–Specify the kinds of objects to create using a prototypical instance 
–Create new objects by copying this prototype
Patterns 
•Builder 
–Separate the construction of a complex object from its representation so that the same construction process can create different representations 
•Composite 
–Compose objects into tree structures to represent part-whole hierarchies 
–Lets clients treat individual objects and compositions of objects uniformly 
•Decorator 
–Attach additional responsibilities to an object dynamically 
–Provide a flexible alternative to subclassingfor extending functionality 
•Adapter 
–Convert the interface of a class into another interface clients expect 
–Lets classes work together that couldn’t otherwise because of incompatible interfaces 
•Bridge 
–Decouple an abstraction from its implementation so that the two can vary independently
Patterns 
•Façade 
–Provide a unified interface to a set of interfaces in a subsystem 
–Defines an higher-level interface that makes the system easier to use 
•Flyweight 
–Use sharing to support large numbers of fine-grained objects efficiently 
•Proxy 
–Provide a surrogate or placeholder for another object to control access to it 
•Iterator 
–Provide a way to access the elements of an aggregate object without exposing its representation 
•Command 
–Encapsulate a request as an object, thereby letting you parameterize clients with different requests
Patterns 
•Interpreter 
–Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language 
•Mediator 
–Define an object that encapsulate how a set of objects interact 
–Promotes loose coupling by keeping objects from referring to each other explicitly 
–Lets you vary their interaction independently 
•Memento 
–Capture and externalize an object’s internal state 
•Observer 
–Define a one-to-many dependency between objects so when one of them change state all its dependents are updated automatically 
•State 
–Allow an object to alter its behavior when its internal state changes 
–The object will appear to change its class
Patterns 
•Visitor 
–Represent an operation to be performed on the elements of an object structure 
–Lets you define a new operation without changing the classes of the elements on which operates 
•Strategy 
–Define a family of algorithms 
–Encapsulate each one 
–Make them interchangeable 
–Lets the algorithms vary independently from clients that use it 
•Chain of responsibilities 
–Avoid coupling the sender of a request to its receiver by giving more then one object a chance to handle the request 
–Chain the receiving objects and pass the request along the chain until an object handles it
Walk Through in Some Patterns
FactoryDefine an interface for creating an object but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses
Factory 
class ProductClass 
{ 
public ProductClass() { … } 
public ProductClass( intaInitValue) { … } 
}; 
class FactoryClass 
{ 
public ProductClassGetNewInstance() 
{ return new ProductClass(); } 
public ProductClassGetNewInstance( intaInitValue) 
{ return new ProductClass( aInitValue); } 
}; 
class Client 
{ 
public void start() 
{ 
// create a new factory 
ProductFactorylFactory= new Factory(); 
// create objects 
ProductClasslObj1 = lFactory.GetNewInstance(); 
ProductClasslObj2 = lFactory.GetNewInstance(4); 
} 
};
Factory 
class ProductClass 
{ 
public ProductClass() { … } 
public ProductClass( intaInitValue) { … } 
}; 
class FactoryClass 
{ 
public ProductClassGetNewInstance() 
{ return new ProductClass(); } 
public ProductClassGetNewInstance( intaInitValue) 
{ return new ProductClass( aInitValue); } 
}; 
class Client 
{ 
public void start() 
{ 
// create a new factory 
ProductFactorylFactory= new Factory(); 
// create objects 
ProductClasslObj1 = lFactory.GetNewInstance(); 
ProductClasslObj2 = lFactory.GetNewInstance(4); 
} 
};
StrategyDefines a family of algorithms, encapsulates each algorithm, andmakes the algorithms interchangeable within that family.
Strategy 
public interface IBehaviour{public intmoveCommand();} 
public class AgressiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){AgressiveBehaviour Behaviour} 
} 
public class DefensiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){DefensiveBehaviour Behaviour} 
} 
public class NormalBehaviourimplements IBehaviour{ 
public intmoveCommand(){NormalBehaviour Behaviour} 
} 
public class Robot { 
IBehaviourbehaviour; 
String name; 
public Robot(String name) 
{this.name = name;} 
public void setBehaviour(IBehaviourbehaviour) 
{this.behaviour= behaviour;} 
public void move() 
{behaviourزmoveCommand();} 
}
Strategy 
public interface IBehaviour{public intmoveCommand();} 
public class AgressiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){AgressiveBehaviour Behaviour} 
} 
public class DefensiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){DefensiveBehaviour Behaviour} 
} 
public class NormalBehaviourimplements IBehaviour{ 
public intmoveCommand(){NormalBehaviour Behaviour} 
} 
public class Robot { 
IBehaviourbehaviour; 
String name; 
public Robot(String name) 
{this.name = name;} 
public void setBehaviour(IBehaviourbehaviour) 
{this.behaviour= behaviour;} 
public void move() 
{behaviourزmoveCommand();} 
} 
Three different Strategies for Robot movement
Strategy 
public interface IBehaviour{public intmoveCommand();} 
public class AgressiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){AgressiveBehaviour Behaviour} 
} 
public class DefensiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){DefensiveBehaviour Behaviour} 
} 
public class NormalBehaviourimplements IBehaviour{ 
public intmoveCommand(){NormalBehaviour Behaviour} 
} 
public class Robot { 
IBehaviourbehaviour; 
String name; 
public Robot(String name) 
{this.name = name;} 
public void setBehaviour(IBehaviourbehaviour) 
{this.behaviour= behaviour;} 
public void move() 
{behaviourزmoveCommand();} 
} 
Assigning a robot behaviour
Strategy 
public interface IBehaviour{public intmoveCommand();} 
public class AgressiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){AgressiveBehaviour Behaviour} 
} 
public class DefensiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){DefensiveBehaviour Behaviour} 
} 
public class NormalBehaviourimplements IBehaviour{ 
public intmoveCommand(){NormalBehaviour Behaviour} 
} 
public class Robot { 
IBehaviourbehaviour; 
String name; 
public Robot(String name) 
{this.name = name;} 
public void setBehaviour(IBehaviourbehaviour) 
{this.behaviour= behaviour;} 
public void move() 
{behaviourزmoveCommand();} 
} 
public static void main(String[] args) { 
Robot r1 = new Robot("Big Robot"); 
Robot r2 = new Robot("George v.2.1"); 
Robot r3 = new Robot("R2"); 
r1.setBehaviour(new AgressiveBehaviour()); 
r2.setBehaviour(new DefensiveBehaviour()); 
r3.setBehaviour(new NormalBehaviour()); 
r1.move(); 
r2.move(); 
r3.move(); 
r1.setBehaviour(new DefensiveBehaviour()); 
r2.setBehaviour(new AgressiveBehaviour()); 
r1.move(); 
r2.move(); 
r3.move(); 
}
Strategy 
public interface IBehaviour{public intmoveCommand();} 
public class AgressiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){AgressiveBehaviour Behaviour} 
} 
public class DefensiveBehaviourimplements IBehaviour{ 
public intmoveCommand(){DefensiveBehaviour Behaviour} 
} 
public class NormalBehaviourimplements IBehaviour{ 
public intmoveCommand(){NormalBehaviour Behaviour} 
} 
public class Robot { 
IBehaviourbehaviour; 
String name; 
public Robot(String name) 
{this.name = name;} 
public void setBehaviour(IBehaviourbehaviour) 
{this.behaviour= behaviour;} 
public void move() 
{behaviourزmoveCommand();} 
} 
public static void main(String[] args) { 
Robot r1 = new Robot("Big Robot"); 
Robot r2 = new Robot("George v.2.1"); 
Robot r3 = new Robot("R2"); 
r1.setBehaviour(new AgressiveBehaviour()); 
r2.setBehaviour(new DefensiveBehaviour()); 
r3.setBehaviour(new NormalBehaviour()); 
r1.move(); 
r2.move(); 
r3.move(); 
r1.setBehaviour(new DefensiveBehaviour()); 
r2.setBehaviour(new AgressiveBehaviour()); 
r1.move(); 
r2.move(); 
r3.move(); 
} 
Simply change the Strategy and the behavior will change
SingletonWhen one, and only one, instance of class is needed. Providing a global point of access to it.
Singleton 
private readonlySqlConnection_sqlConnection; 
constCONNECTION_STRING = (@"Data Source=127.0.0.1;database=soa;Userid=sa1;Password=sa1;“; 
public static SqlConnectionGetSqlConnectionSingleton() 
{ 
if (_sqlConnection== null) 
{ 
_sqlConnection= new SqlConnection(CONNECTION_STRING ); 
} 
return _sqlConnection; 
} 
Any client will call GetSqlConnectionSingleton(public) and has no direct access to _sqlConnection(private)
Singleton for an Object 
publicsealedclassSingleton 
{ 
privatestaticSingleton _instance; 
privateSingleton() { } 
publicstaticSingleton GetSingleton() 
{ 
if(_instance == null) _instance = newSingleton(); 
return_instance; 
} 
} 
No one can instantiate this (since the constructor is private), like this: 
Singleton s = new Singleton();
Singleton for an Object 
publicsealedclassSingleton 
{ 
privatestaticSingleton _instance; 
privateSingleton() { } 
publicstaticSingleton GetSingleton() 
{ 
if(_instance == null) _instance = newSingleton(); 
return_instance; 
} 
} 
One Instance and One Instance Only will be Created for this Class Object
Database ConnectionSingleton 
private readonlySqlConnection_sqlConnection; 
constCONNECTION_STRING = (@"Data Source=127.0.0.1;database=soa;Userid=sa1;Password=sa1;“; 
public static SqlConnectionGetSqlConnectionSingleton() 
{ 
if (_sqlConnection== null) 
{ 
_sqlConnection= new SqlConnection(CONNECTION_STRING ); 
} 
return _sqlConnection; 
}
Database Connection Singleton 
private readonlySqlConnection_sqlConnection; 
constCONNECTION_STRING = (@"Data Source=127.0.0.1;database=soa;Userid=sa1;Password=sa1;“; 
public static SqlConnectionGetSqlConnectionSingleton() 
{ 
if (_sqlConnection== null) 
{ 
_sqlConnection= new SqlConnection(CONNECTION_STRING ); 
} 
return _sqlConnection; 
}
Singleton for an Object in Multi-threaded Application? Any Need to Adjust?
Singleton for an Object in Multi-threaded Application 
publicsealedclassSingleton 
{ 
privatestaticSingleton _instance; 
privatestaticobject_lockThis= newobject(); 
privateSingleton() { } 
publicstaticSingleton GetSingleton() 
{ 
lock(_lockThis) 
{ 
if(_instance == null) _instance = newSingleton(); 
} 
return_instance; 
} 
}
MultitonIs an extension of the singleton pattern. When one, and only one, instance of class is needed that corresponds to a key. Providing a global point of access to it.
Multiton 
Dictionary<Key, SingletonObject> _singletonInstances; 
publicstaticSingletonInstancesGetMultiton(stringkey) 
{ 
lock(_lock) 
{ 
if(!_singletonInstances.ContainsKey(key)) _singletonInstances.Add(key, newMultiton()); 
} 
return_instances[key]; 
}
Multiton 
Dictionary<Key, SingletonObject> _singletonInstances; 
publicstaticSingletonInstancesGetMultiton(stringkey) 
{ 
lock(_lock) 
{ 
if(!_singletonInstances.ContainsKey(key)) _singletonInstances.Add(key, newMultiton()); 
} 
return_instances[key]; 
}
Software Architectural Patterns
MVCModel View Controller
MVVMModel View ViewModel

More Related Content

What's hot

Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScripttonyh1
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGI
Aashish Jain
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Functions in javascript
Functions in javascriptFunctions in javascript
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
Sagar Verma
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
akreyi
 

What's hot (20)

Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGI
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 

Similar to C# Advanced L07-Design Patterns

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
Design patterns
Design patternsDesign patterns
Design patterns
Anas Alpure
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
Ólafur Andri Ragnarsson
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)stanbridge
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
Lalit Kale
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
bonej010
 
Design patterns
Design patternsDesign patterns
Design patternsAlok Guha
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingAllan Mangune
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur University
Shubham Narkhede
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 

Similar to C# Advanced L07-Design Patterns (20)

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Object-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & ProgrammingObject-oriented Analysis, Design & Programming
Object-oriented Analysis, Design & Programming
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur University
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 

More from Mohammad Shaker

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
Mohammad Shaker
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Mohammad Shaker
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
Mohammad Shaker
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
Mohammad Shaker
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
Mohammad Shaker
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
Mohammad Shaker
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
Mohammad Shaker
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
Mohammad Shaker
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
Mohammad Shaker
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
Mohammad Shaker
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
Mohammad Shaker
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
Mohammad Shaker
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
Mohammad Shaker
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
Mohammad Shaker
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
Mohammad Shaker
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
Mohammad Shaker
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
Mohammad Shaker
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
Mohammad Shaker
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
Mohammad Shaker
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
Mohammad Shaker
 

More from Mohammad Shaker (20)

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 

Recently uploaded

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 

Recently uploaded (20)

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 

C# Advanced L07-Design Patterns

  • 1. Mohammad Shaker mohammadshaker.com @ZGTRShaker 2011, 2012, 2013, 2014 C# Advanced L07–Design Patterns
  • 2. Gang of Four(GoF) Gamma, Helm, Johnson, Vlissides
  • 3. Gamma et al, Design Patterns: Elements of Reusable Object-Oriented SoftwareAddison Wesley, 1995
  • 4. Scope •Patterns solve software structural problems like: –Abstraction, –Encapsulation –Information hiding –Separation of concerns –Coupling and cohesion –Separation of interface and implementation –Single point of reference –Divide and conquer •Patterns also solve non-functional problems like: –Changeability –Interoperability –Efficiency –Reliability –Testability –Reusability
  • 5. Types of Pattern •There are 3 types of pattern: –Creational: address problems of creating an object in a flexible way. Separate creation, from operation/use. –Structural: address problems of using O-O constructs like inheritance to organize classes and objects –Behavioral: address problems of assigning responsibilities to classes. Suggest both static relationships and patterns of communication
  • 6. Classification of Design Patterns Purpose Creational Structural Behavioral Factory Method Adapter Interpreter Abstract Factory Bridge Template Method Builder Composite Chain of Responsibility Prototype Decorator Command Singleton Façade Iterator Flyweight Mediator Proxy Memento Observer State Strategy Visitor
  • 8. Patterns •Singleton –Ensure a class only has one instance –Provide a global point of access to it •Abstract Factory –Provide an interface for creating families of related or dependent objects without specifying their concrete classes •Factory Method –Define an interface for creating an object but let subclasses decide which class to instantiate –Lets a class defer instantiation to subclasses •Prototype –Specify the kinds of objects to create using a prototypical instance –Create new objects by copying this prototype
  • 9. Patterns •Builder –Separate the construction of a complex object from its representation so that the same construction process can create different representations •Composite –Compose objects into tree structures to represent part-whole hierarchies –Lets clients treat individual objects and compositions of objects uniformly •Decorator –Attach additional responsibilities to an object dynamically –Provide a flexible alternative to subclassingfor extending functionality •Adapter –Convert the interface of a class into another interface clients expect –Lets classes work together that couldn’t otherwise because of incompatible interfaces •Bridge –Decouple an abstraction from its implementation so that the two can vary independently
  • 10. Patterns •Façade –Provide a unified interface to a set of interfaces in a subsystem –Defines an higher-level interface that makes the system easier to use •Flyweight –Use sharing to support large numbers of fine-grained objects efficiently •Proxy –Provide a surrogate or placeholder for another object to control access to it •Iterator –Provide a way to access the elements of an aggregate object without exposing its representation •Command –Encapsulate a request as an object, thereby letting you parameterize clients with different requests
  • 11. Patterns •Interpreter –Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language •Mediator –Define an object that encapsulate how a set of objects interact –Promotes loose coupling by keeping objects from referring to each other explicitly –Lets you vary their interaction independently •Memento –Capture and externalize an object’s internal state •Observer –Define a one-to-many dependency between objects so when one of them change state all its dependents are updated automatically •State –Allow an object to alter its behavior when its internal state changes –The object will appear to change its class
  • 12. Patterns •Visitor –Represent an operation to be performed on the elements of an object structure –Lets you define a new operation without changing the classes of the elements on which operates •Strategy –Define a family of algorithms –Encapsulate each one –Make them interchangeable –Lets the algorithms vary independently from clients that use it •Chain of responsibilities –Avoid coupling the sender of a request to its receiver by giving more then one object a chance to handle the request –Chain the receiving objects and pass the request along the chain until an object handles it
  • 13. Walk Through in Some Patterns
  • 14. FactoryDefine an interface for creating an object but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses
  • 15. Factory class ProductClass { public ProductClass() { … } public ProductClass( intaInitValue) { … } }; class FactoryClass { public ProductClassGetNewInstance() { return new ProductClass(); } public ProductClassGetNewInstance( intaInitValue) { return new ProductClass( aInitValue); } }; class Client { public void start() { // create a new factory ProductFactorylFactory= new Factory(); // create objects ProductClasslObj1 = lFactory.GetNewInstance(); ProductClasslObj2 = lFactory.GetNewInstance(4); } };
  • 16. Factory class ProductClass { public ProductClass() { … } public ProductClass( intaInitValue) { … } }; class FactoryClass { public ProductClassGetNewInstance() { return new ProductClass(); } public ProductClassGetNewInstance( intaInitValue) { return new ProductClass( aInitValue); } }; class Client { public void start() { // create a new factory ProductFactorylFactory= new Factory(); // create objects ProductClasslObj1 = lFactory.GetNewInstance(); ProductClasslObj2 = lFactory.GetNewInstance(4); } };
  • 17. StrategyDefines a family of algorithms, encapsulates each algorithm, andmakes the algorithms interchangeable within that family.
  • 18. Strategy public interface IBehaviour{public intmoveCommand();} public class AgressiveBehaviourimplements IBehaviour{ public intmoveCommand(){AgressiveBehaviour Behaviour} } public class DefensiveBehaviourimplements IBehaviour{ public intmoveCommand(){DefensiveBehaviour Behaviour} } public class NormalBehaviourimplements IBehaviour{ public intmoveCommand(){NormalBehaviour Behaviour} } public class Robot { IBehaviourbehaviour; String name; public Robot(String name) {this.name = name;} public void setBehaviour(IBehaviourbehaviour) {this.behaviour= behaviour;} public void move() {behaviourزmoveCommand();} }
  • 19. Strategy public interface IBehaviour{public intmoveCommand();} public class AgressiveBehaviourimplements IBehaviour{ public intmoveCommand(){AgressiveBehaviour Behaviour} } public class DefensiveBehaviourimplements IBehaviour{ public intmoveCommand(){DefensiveBehaviour Behaviour} } public class NormalBehaviourimplements IBehaviour{ public intmoveCommand(){NormalBehaviour Behaviour} } public class Robot { IBehaviourbehaviour; String name; public Robot(String name) {this.name = name;} public void setBehaviour(IBehaviourbehaviour) {this.behaviour= behaviour;} public void move() {behaviourزmoveCommand();} } Three different Strategies for Robot movement
  • 20. Strategy public interface IBehaviour{public intmoveCommand();} public class AgressiveBehaviourimplements IBehaviour{ public intmoveCommand(){AgressiveBehaviour Behaviour} } public class DefensiveBehaviourimplements IBehaviour{ public intmoveCommand(){DefensiveBehaviour Behaviour} } public class NormalBehaviourimplements IBehaviour{ public intmoveCommand(){NormalBehaviour Behaviour} } public class Robot { IBehaviourbehaviour; String name; public Robot(String name) {this.name = name;} public void setBehaviour(IBehaviourbehaviour) {this.behaviour= behaviour;} public void move() {behaviourزmoveCommand();} } Assigning a robot behaviour
  • 21. Strategy public interface IBehaviour{public intmoveCommand();} public class AgressiveBehaviourimplements IBehaviour{ public intmoveCommand(){AgressiveBehaviour Behaviour} } public class DefensiveBehaviourimplements IBehaviour{ public intmoveCommand(){DefensiveBehaviour Behaviour} } public class NormalBehaviourimplements IBehaviour{ public intmoveCommand(){NormalBehaviour Behaviour} } public class Robot { IBehaviourbehaviour; String name; public Robot(String name) {this.name = name;} public void setBehaviour(IBehaviourbehaviour) {this.behaviour= behaviour;} public void move() {behaviourزmoveCommand();} } public static void main(String[] args) { Robot r1 = new Robot("Big Robot"); Robot r2 = new Robot("George v.2.1"); Robot r3 = new Robot("R2"); r1.setBehaviour(new AgressiveBehaviour()); r2.setBehaviour(new DefensiveBehaviour()); r3.setBehaviour(new NormalBehaviour()); r1.move(); r2.move(); r3.move(); r1.setBehaviour(new DefensiveBehaviour()); r2.setBehaviour(new AgressiveBehaviour()); r1.move(); r2.move(); r3.move(); }
  • 22. Strategy public interface IBehaviour{public intmoveCommand();} public class AgressiveBehaviourimplements IBehaviour{ public intmoveCommand(){AgressiveBehaviour Behaviour} } public class DefensiveBehaviourimplements IBehaviour{ public intmoveCommand(){DefensiveBehaviour Behaviour} } public class NormalBehaviourimplements IBehaviour{ public intmoveCommand(){NormalBehaviour Behaviour} } public class Robot { IBehaviourbehaviour; String name; public Robot(String name) {this.name = name;} public void setBehaviour(IBehaviourbehaviour) {this.behaviour= behaviour;} public void move() {behaviourزmoveCommand();} } public static void main(String[] args) { Robot r1 = new Robot("Big Robot"); Robot r2 = new Robot("George v.2.1"); Robot r3 = new Robot("R2"); r1.setBehaviour(new AgressiveBehaviour()); r2.setBehaviour(new DefensiveBehaviour()); r3.setBehaviour(new NormalBehaviour()); r1.move(); r2.move(); r3.move(); r1.setBehaviour(new DefensiveBehaviour()); r2.setBehaviour(new AgressiveBehaviour()); r1.move(); r2.move(); r3.move(); } Simply change the Strategy and the behavior will change
  • 23. SingletonWhen one, and only one, instance of class is needed. Providing a global point of access to it.
  • 24. Singleton private readonlySqlConnection_sqlConnection; constCONNECTION_STRING = (@"Data Source=127.0.0.1;database=soa;Userid=sa1;Password=sa1;“; public static SqlConnectionGetSqlConnectionSingleton() { if (_sqlConnection== null) { _sqlConnection= new SqlConnection(CONNECTION_STRING ); } return _sqlConnection; } Any client will call GetSqlConnectionSingleton(public) and has no direct access to _sqlConnection(private)
  • 25. Singleton for an Object publicsealedclassSingleton { privatestaticSingleton _instance; privateSingleton() { } publicstaticSingleton GetSingleton() { if(_instance == null) _instance = newSingleton(); return_instance; } } No one can instantiate this (since the constructor is private), like this: Singleton s = new Singleton();
  • 26. Singleton for an Object publicsealedclassSingleton { privatestaticSingleton _instance; privateSingleton() { } publicstaticSingleton GetSingleton() { if(_instance == null) _instance = newSingleton(); return_instance; } } One Instance and One Instance Only will be Created for this Class Object
  • 27. Database ConnectionSingleton private readonlySqlConnection_sqlConnection; constCONNECTION_STRING = (@"Data Source=127.0.0.1;database=soa;Userid=sa1;Password=sa1;“; public static SqlConnectionGetSqlConnectionSingleton() { if (_sqlConnection== null) { _sqlConnection= new SqlConnection(CONNECTION_STRING ); } return _sqlConnection; }
  • 28. Database Connection Singleton private readonlySqlConnection_sqlConnection; constCONNECTION_STRING = (@"Data Source=127.0.0.1;database=soa;Userid=sa1;Password=sa1;“; public static SqlConnectionGetSqlConnectionSingleton() { if (_sqlConnection== null) { _sqlConnection= new SqlConnection(CONNECTION_STRING ); } return _sqlConnection; }
  • 29. Singleton for an Object in Multi-threaded Application? Any Need to Adjust?
  • 30. Singleton for an Object in Multi-threaded Application publicsealedclassSingleton { privatestaticSingleton _instance; privatestaticobject_lockThis= newobject(); privateSingleton() { } publicstaticSingleton GetSingleton() { lock(_lockThis) { if(_instance == null) _instance = newSingleton(); } return_instance; } }
  • 31. MultitonIs an extension of the singleton pattern. When one, and only one, instance of class is needed that corresponds to a key. Providing a global point of access to it.
  • 32. Multiton Dictionary<Key, SingletonObject> _singletonInstances; publicstaticSingletonInstancesGetMultiton(stringkey) { lock(_lock) { if(!_singletonInstances.ContainsKey(key)) _singletonInstances.Add(key, newMultiton()); } return_instances[key]; }
  • 33. Multiton Dictionary<Key, SingletonObject> _singletonInstances; publicstaticSingletonInstancesGetMultiton(stringkey) { lock(_lock) { if(!_singletonInstances.ContainsKey(key)) _singletonInstances.Add(key, newMultiton()); } return_instances[key]; }