HI WELCOME TO SIRIS
Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Abstract Factory Design Pattern - C#

Abstract Factory method pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to create a set of related objects, or dependent objects. Internally, Abstract Factory use Factory design pattern for creating objects. It may also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects. In this article, I would like share what is abstract factory pattern and how is it work?

What is Abstract Factory Pattern?

Abstract Factory patterns acts a super-factory which creates other factories. This pattern is also called as Factory of factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.

Abstract Factory Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the abstract factory design pattern is given below:


The classes, interfaces and objects in the above UML class diagram are as follows:
  1. AbstractFactory

    This is an interface which is used to create abstract product
  2. ConcreteFactory

    This is a class which implements the AbstractFactory interface to create concrete products.
  3. AbstractProduct

    This is an interface which declares a type of product.
  4. ConcreteProduct

    This is a class which implements the AbstractProduct interface to create product.
  5. Client

    This is a class which use AbstractFactory and AbstractProduct interfaces to create a family of related objects.

C# - Implementation Code

  1. public interface AbstractFactory
  2. {
  3. AbstractProductA CreateProductA();
  4. AbstractProductB CreateProductB();
  5. }
  6. public class ConcreteFactoryA : AbstractFactory
  7. {
  8. public AbstractProductA CreateProductA()
  9. {
  10. return new ProductA1();
  11. }
  12. public AbstractProductB CreateProductB()
  13. {
  14. return new ProductB1();
  15. }
  16. }
  17. public class ConcreteFactoryB : AbstractFactory
  18. {
  19. public AbstractProductA CreateProductA()
  20. {
  21. return new ProductA2();
  22. }
  23. public AbstractProductB CreateProductB()
  24. {
  25. return new ProductB2();
  26. }
  27. }
  28. public interface AbstractProductA { }
  29. public class ProductA1 : AbstractProductA { }
  30. public class ProductA2 : AbstractProductA { }
  31. public interface AbstractProductB { }
  32. public class ProductB1 : AbstractProductB { }
  33. public class ProductB2 : AbstractProductB { }
  34.  
  35. public class Client
  36. {
  37. private AbstractProductA _productA;
  38. private AbstractProductB _productB;
  39. public Client(AbstractFactory factory)
  40. {
  41. _productA = factory.CreateProductA();
  42. _productB = factory.CreateProductB();
  43. }
  44. }

Abstract Factory Pattern - Example

 

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. VehicleFactory - AbstractFactory interface
  2. HondaFactory & HeroFactory- Concrete Factories
  3. Bike & Scooter - AbstractProduct interface
  4. Regular Bike, Sports Bike, Regular Scooter & Scooty - Concreate Products
  5. VehicleClient - Client

C# - Sample Code

  1. /// <summary>
  2. /// The 'AbstractFactory' interface.
  3. /// </summary>
  4. interface VehicleFactory
  5. {
  6. Bike GetBike(string Bike);
  7. Scooter GetScooter(string Scooter);
  8. }
  9.  
  10. /// <summary>
  11. /// The 'ConcreteFactory1' class.
  12. /// </summary>
  13. class HondaFactory : VehicleFactory
  14. {
  15. public Bike GetBike(string Bike)
  16. {
  17. switch (Bike)
  18. {
  19. case "Sports":
  20. return new SportsBike();
  21. case "Regular":
  22. return new RegularBike();
  23. default:
  24. throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Bike));
  25. }
  26.  
  27. }
  28.  
  29. public Scooter GetScooter(string Scooter)
  30. {
  31. switch (Scooter)
  32. {
  33. case "Sports":
  34. return new Scooty();
  35. case "Regular":
  36. return new RegularScooter();
  37. default:
  38. throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Scooter));
  39. }
  40.  
  41. }
  42. }
  43.  
  44. /// <summary>
  45. /// The 'ConcreteFactory2' class.
  46. /// </summary>
  47. class HeroFactory : VehicleFactory
  48. {
  49. public Bike GetBike(string Bike)
  50. {
  51. switch (Bike)
  52. {
  53. case "Sports":
  54. return new SportsBike();
  55. case "Regular":
  56. return new RegularBike();
  57. default:
  58. throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Bike));
  59. }
  60.  
  61. }
  62.  
  63. public Scooter GetScooter(string Scooter)
  64. {
  65. switch (Scooter)
  66. {
  67. case "Sports":
  68. return new Scooty();
  69. case "Regular":
  70. return new RegularScooter();
  71. default:
  72. throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Scooter));
  73. }
  74.  
  75. }
  76. }
  77.  
  78. /// <summary>
  79. /// The 'AbstractProductA' interface
  80. /// </summary>
  81. interface Bike
  82. {
  83. string Name();
  84. }
  85.  
  86. /// <summary>
  87. /// The 'AbstractProductB' interface
  88. /// </summary>
  89. interface Scooter
  90. {
  91. string Name();
  92. }
  93.  
  94. /// <summary>
  95. /// The 'ProductA1' class
  96. /// </summary>
  97. class RegularBike : Bike
  98. {
  99. public string Name()
  100. {
  101. return "Regular Bike- Name";
  102. }
  103. }
  104.  
  105. /// <summary>
  106. /// The 'ProductA2' class
  107. /// </summary>
  108. class SportsBike : Bike
  109. {
  110. public string Name()
  111. {
  112. return "Sports Bike- Name";
  113. }
  114. }
  115.  
  116. /// <summary>
  117. /// The 'ProductB1' class
  118. /// </summary>
  119. class RegularScooter : Scooter
  120. {
  121. public string Name()
  122. {
  123. return "Regular Scooter- Name";
  124. }
  125. }
  126.  
  127. /// <summary>
  128. /// The 'ProductB2' class
  129. /// </summary>
  130. class Scooty : Scooter
  131. {
  132. public string Name()
  133. {
  134. return "Scooty- Name";
  135. }
  136. }
  137.  
  138. /// <summary>
  139. /// The 'Client' class
  140. /// </summary>
  141. class VehicleClient
  142. {
  143. Bike bike;
  144. Scooter scooter;
  145.  
  146. public VehicleClient(VehicleFactory factory, string type)
  147. {
  148. bike = factory.GetBike(type);
  149. scooter = factory.GetScooter(type);
  150. }
  151.  
  152. public string GetBikeName()
  153. {
  154. return bike.Name();
  155. }
  156.  
  157. public string GetScooterName()
  158. {
  159. return scooter.Name();
  160. }
  161.  
  162. }
  163.  
  164. /// <summary>
  165. /// Abstract Factory Pattern Demo
  166. /// </summary>
  167. class Program
  168. {
  169. static void Main(string[] args)
  170. {
  171. VehicleFactory honda = new HondaFactory();
  172. VehicleClient hondaclient = new VehicleClient(honda, "Regular");
  173. Console.WriteLine("******* Honda **********");
  174. Console.WriteLine(hondaclient.GetBikeName());
  175. Console.WriteLine(hondaclient.GetScooterName());
  176. hondaclient = new VehicleClient(honda, "Sports");
  177. Console.WriteLine(hondaclient.GetBikeName());
  178. Console.WriteLine(hondaclient.GetScooterName());
  179. VehicleFactory hero = new HeroFactory();
  180. VehicleClient heroclient = new VehicleClient(hero, "Regular");
  181. Console.WriteLine("******* Hero **********");
  182. Console.WriteLine(heroclient.GetBikeName());
  183. Console.WriteLine(heroclient.GetScooterName());
  184. heroclient = new VehicleClient(hero, "Sports");
  185. Console.WriteLine(heroclient.GetBikeName());
  186. Console.WriteLine(heroclient.GetScooterName());
  187. Console.ReadKey();
  188. }
  189. }

Abstract Factory Pattern Demo - Output

When to use it?

  1. Create a set of related objects, or dependent objects which must be used together.
  2. System should be configured to work with multiple families of products.
  3. The creation of objects should be independent from the utilizing system.
  4. Concrete classes should be decoupled from clients.

Note

  1. Internally, Abstract Factory use Factory design pattern for creating objects. But it can also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects.
  2. Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
  3. When Abstract Factory, Builder, and Prototype define a factory for creating the objects, we should consider the following points :
    1. Abstract Factory use the factory for creating objects of several classes.
    2. Builder use the factory for creating a complex object by using simple objects and a step by step approach.
    3. Prototype use the factory for building a object by copying an existing object.
What do you think?
I hope you will enjoy the Abstract Factory Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Factory Method Design Pattern - C#

The factory method design pattern abstract the process of object creation and allows the object to be created at run-time when it is required. Factory method pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to create objects. People usually use this pattern as the standard way to create objects. In this article, I would like to share what is factory pattern and how it works?

What is Factory Method Pattern?

In Factory pattern, we create the object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.
In short, factory method design pattern abstract the process of object creation and allows the object to be created at run-time when it is required.

Factory Method Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the factory method design pattern is given below: 
 

The classes, interfaces and objects in the above UML class diagram are as follows:
  1. Product

    This is an interface for creating the objects.
  2. ConcreteProduct

    This is a class which implements the Product interface.
  3. Creator

    This is an abstract class and declares the factory method, which returns an object of type Product.
  4. ConcreteCreator

    This is a class which implements the Creator class and overrides the factory method to return an instance of a ConcreteProduct.

C# - Implementation Code

  1. interface Product
  2. {
  3.  
  4. }
  5.  
  6. class ConcreteProductA : Product
  7. {
  8. }
  9.  
  10. class ConcreteProductB : Product
  11. {
  12. }
  13.  
  14. abstract class Creator
  15. {
  16. public abstract Product FactoryMethod(string type);
  17. }
  18.  
  19. class ConcreteCreator : Creator
  20. {
  21. public override Product FactoryMethod(string type)
  22. {
  23. switch (type)
  24. {
  25. case "A": return new ConcreteProductA();
  26. case "B": return new ConcreteProductB();
  27. default: throw new ArgumentException("Invalid type", "type");
  28. }
  29. }
  30. }

Factory Method Pattern - Example

 

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. IFactory - Interface
  2. Scooter & Bike - Concreate Product classes
  3. VehicleFactory - Creator
  4. ConcreteVehicleFactory - Concreate Creator

C# - Sample Code

  1. using System;
  2. namespace Factory
  3. {
  4. /// <summary>
  5. /// The 'Product' interface
  6. /// </summary>
  7. public interface IFactory
  8. {
  9. void Drive(int miles);
  10. }
  11.  
  12. /// <summary>
  13. /// A 'ConcreteProduct' class
  14. /// </summary>
  15. public class Scooter : IFactory
  16. {
  17. public void Drive(int miles)
  18. {
  19. Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
  20. }
  21. }
  22.  
  23. /// <summary>
  24. /// A 'ConcreteProduct' class
  25. /// </summary>
  26. public class Bike : IFactory
  27. {
  28. public void Drive(int miles)
  29. {
  30. Console.WriteLine("Drive the Bike : " + miles.ToString() + "km");
  31. }
  32. }
  33.  
  34. /// <summary>
  35. /// The Creator Abstract Class
  36. /// </summary>
  37. public abstract class VehicleFactory
  38. {
  39. public abstract IFactory GetVehicle(string Vehicle);
  40.  
  41. }
  42.  
  43. /// <summary>
  44. /// A 'ConcreteCreator' class
  45. /// </summary>
  46. public class ConcreteVehicleFactory : VehicleFactory
  47. {
  48. public override IFactory GetVehicle(string Vehicle)
  49. {
  50. switch (Vehicle)
  51. {
  52. case "Scooter":
  53. return new Scooter();
  54. case "Bike":
  55. return new Bike();
  56. default:
  57. throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
  58. }
  59. }
  60.  
  61. }
  62. /// <summary>
  63. /// Factory Pattern Demo
  64. /// </summary>
  65. class Program
  66. {
  67. static void Main(string[] args)
  68. {
  69. VehicleFactory factory = new ConcreteVehicleFactory();
  70.  
  71. IFactory scooter = factory.GetVehicle("Scooter");
  72. scooter.Drive(10);
  73.  
  74. IFactory bike = factory.GetVehicle("Bike");
  75. bike.Drive(20);
  76.  
  77. Console.ReadKey();
  78.  
  79. }
  80. }
  81. }

Factory Pattern Demo - Output

When to use it?

  1. Subclasses figure out what objects should be created.
  2. Parent class allows later instantiation to subclasses means the creation of object is done when it is required.
  3. The process of objects creation is required to centralize within the application.
  4. A class (creator) will not know what classes it will be required to create.
What do you think?
I hope you will enjoy the Factory Method Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Gang of Four (GOF) Design Patterns in .NET

In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book (Design Patterns: Elements of Reusable Object-Oriented Software) for explaining the concept of Design Pattern in Software development. These four authors are collectively known as Gang of Four (GOF).

GOF Design Patterns

The 23 Design patterns are defined by the Gang of Four programmers. These 23 patterns are divided into three groups depending on the nature of the design problem they intend to solve.
  1. Creational Design Patterns

    These patterns deal with the process of objects creation in such a way that they can be decoupled from their implementing system. This provides more flexibility in deciding which objects need to be created for a given use case/ scenario. There are as follows:
    1. Factory Method : Create instances of derived classes
    2. Abstract Factory : Create instances of several classes belonging to different families
    3. Builder : Separates an object construction from its representation
    4. Prototype : Create a duplicate object or clone of the object
    5. Singleton : Ensures that a class can has only one instance
  2. Structural Design Patterns

    These patterns deal with the composition of objects structures. The concept of inheritance is used to compose interfaces and define various ways to compose objects for obtaining new functionalities. There are as follows:
    1. Adapter : Match interfaces of different classes
    2. Bridge : Separates an object’s abstraction from its implementation
    3. Composite : A tree structure of simple and composite objects
    4. Decorator : Add responsibilities to objects dynamically
    5. Façade : A single class that represents an entire complex system
    6. Flyweight : Minimize memory usage by sharing as much data as possible with similar objects
    7. Proxy : Provides a surrogate object, which references to other object
  3. Behavioral Design Patterns

    These patterns deal with the process of communication, managing relationships, and responsibilities between objects. There are as follows:
    1. Chain of Responsibility: Passes a request among a list or chain of objects.
    2. Command: Wraps a request under an object as a command and passed to invoker object.
    3. Interpreter: Implements an expression interface to interpret a particular context.
    4. Iterator: Provides a way to access the elements of a collection object in sequential manner without knowing its underlying structure.
    5. Mediator: Allows multiple objects to communicate with each other’s without knowing each other’s structure.
    6. Memento: Capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
    7. Observer: Allows an object (subject) to publish changes to its state and other objects (observer) that depend upon that object are automatically notified of any changes to the subject's state.
    8. State: Alters the behavior of an object when it’s internal state changes.
    9. Strategy: Allows a client to choose an algorithm from a family of algorithms at run-time and gives it a simple way to access it.
    10. Visitor: Creates and performs new operations onto a set of objects without changing the object structure or classes.
    11. Template Method: Defines the basic steps of an algorithm and allow the implementation of the individual steps to be changed.
What do you think?
I hope you will enjoy the GOF design patterns while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Different Types of Design Patterns

Design patterns provide solutions to common problems which occur in software design. Design patterns are about reusable designs and interactions of objects.

Types of Design Patterns

These can be organized in 4 separate pattern groups depending on the nature of the design problem they intend to solve.
  1. Gang of Four Patterns
  2. Enterprise Patterns
  3. SOA and Messaging Patterns
  4. Model-View Patterns

Advantages of Design Patterns

Design Patterns have following main advantages in software development.
  1. Provide solutions to common problems which occur in software design.
  2. Provide common platform for developers means developer can implement these in any language.
  3. Provide a standard terminology and are specific to particular scenario.
What do you think?
I hope you will enjoy the design patterns while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Different Types of Software Design Principles

Software design principles are a set of guidelines that helps developers to make a good system design. The most important principle is SOLID principle. The key software design principles are as:
  1. SOILD

    It is combination of five basic designing principles.
    1. Single Responsibility Principle (SRP)

      This principle states that there should never be more than one reason for a class to change. This means that you should design your classes in such a way that each class should have a single purpose.
      Example - An Account class is responsible for managing Current and Saving Account but a CurrentAccount and a SavingAccount classes would be responsible for managing current and saving accounts respectively. Hence both are responsible for single purpose only. Hence we are moving towards specialization.
    2. Open/Closed Principle (OCP)

      This principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. The "closed" part of the rule states that once a module has been developed and tested, the code should only be changed to correct bugs. The "open" part says that you should be able to extend existing code in order to introduce new functionality.
      Example – A PaymentGateway base class contains all basic payment related properties and methods. This class can be extended by different PaymentGateway classes for different payment gateway vendors to achieve theirs functionalities. Hence it is open for extension but closed for modification.
    3. Liscov Substitution Principle (LSP)

      This principle states that functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
      Example - Assume that you have an inheritance hierarchy with Person and Student. Wherever you can use Person, you should also be able to use a Student, because Student is a subclass of Person.
    4. Interface Segregation Principle (ISP)

      This principle states that Clients should not be forced to depend upon interfaces that they don’t use. This means the number of members in the interface that is visible to the dependent class should be minimized.
      Example - The service interface that is exposed to the client should contains only client related methods not all.
    5. Dependency Inversion Principle (DIP)

      The Dependency Inversion Principle states that:
      1. High level modules should not depend upon low level modules. Both should depend upon abstractions.
      2. Abstractions should not depend upon details. Details should depend upon abstractions.
      It helps us to develop loosely couple code by ensuring that high-level modules depend on abstractions rather than concrete implementations of lower-level modules. The Dependency Injection pattern is an implementation of this principle
      Example - The Dependency Injection pattern is an implementation of this principle
  2. DRY (Don’t Repeat Yourself)

    This principle states that each small pieces of knowledge (code) may only occur exactly once in the entire system. This helps us to write scalable, maintainable and reusable code.
    Example – Asp.Net MVC framework works on this principle.
  3. KISS (Keep it simple, Stupid!)

    This principle states that try to keep each small piece of software simple and unnecessary complexity should be avoided. This helps us to write easy maintainable code.
  4. YAGNI (You ain't gonna need it)

    This principle states that always implement things when you actually need them never implements things before you need them.
What do you think?
I hope you will enjoy the design principles while designing your application. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.