Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

C# Advanced L07-Design Patterns

C# Advanced L07-Desgin Patterns

  • Be the first to comment

C# Advanced L07-Design Patterns

  1. 1. Mohammad Shaker mohammadshaker.com @ZGTRShaker 2011, 2012, 2013, 2014 C# Advanced L07–Design Patterns
  2. 2. Gang of Four(GoF) Gamma, Helm, Johnson, Vlissides
  3. 3. Gamma et al, Design Patterns: Elements of Reusable Object-Oriented SoftwareAddison Wesley, 1995
  4. 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. 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. 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
  7. 7. Patterns
  8. 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. 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. 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. 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. 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. 13. Walk Through in Some Patterns
  14. 14. FactoryDefine an interface for creating an object but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses
  15. 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. 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. 17. StrategyDefines a family of algorithms, encapsulates each algorithm, andmakes the algorithms interchangeable within that family.
  18. 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. 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. 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. 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. 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. 23. SingletonWhen one, and only one, instance of class is needed. Providing a global point of access to it.
  24. 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. 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. 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. 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. 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. 29. Singleton for an Object in Multi-threaded Application? Any Need to Adjust?
  30. 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. 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. 32. Multiton Dictionary<Key, SingletonObject> _singletonInstances; publicstaticSingletonInstancesGetMultiton(stringkey) { lock(_lock) { if(!_singletonInstances.ContainsKey(key)) _singletonInstances.Add(key, newMultiton()); } return_instances[key]; }
  33. 33. Multiton Dictionary<Key, SingletonObject> _singletonInstances; publicstaticSingletonInstancesGetMultiton(stringkey) { lock(_lock) { if(!_singletonInstances.ContainsKey(key)) _singletonInstances.Add(key, newMultiton()); } return_instances[key]; }
  34. 34. Software Architectural Patterns
  35. 35. MVCModel View Controller
  36. 36. MVVMModel View ViewModel

×