Design Patterns (.NET)
What are design patterns?
To solve software design problems that we face on regular basis, design patterns are the solution. Design patterns are all about reusable designs, object generation and integration.? There are 23 design patterns (also known as Gang of Four Design Patterns) which are grouped into three major categories.?
Creational Design Pattern
Structural Design Patterns
Behavioral Design Patterns
Creational Design Patterns:
Creational Design Pattern deals with the process of object creation and initialization. It gives a programmer more flexibility in which objects need to be created for the current given case.?
Factory? Method is widely used to provide high-level flexibility for your code. It can be recognized by the creation method that creates an object from concrete classes but returns them as objects of abstract type or interface.
What is the Factory Method?
Factory method is a pattern where we create the object without exposing its creation logic by using an interface, but let the subclass decide which class to instantiate. It can be said that the factory method abstracts the process of object creation and allows the object to be created at run-time when required.
UML Diagram:
Implementational Example (pseudo):
interface Product {
class ConcreteProductA : Product
{
}
class ConcreteProductB : Product
{
}
abstract class Creator
{
??public abstract Product FactoryMethod(string type);
}
class ConcreteCreator : Creator
{
?public override Product FactoryMethod(string type)
?{
?switch (type)
?{
?case "A": return new ConcreteProductA();
?case "B": return new ConcreteProductB();
?default: throw new ArgumentException("Invalid type", "type");
?}
?}
}
Sample:?
using System;
namespace Factory
{
?/// The 'Product' interface
?public interface IFactory
?{
????void Drive(int miles);
?}
?/// A 'ConcreteProduct' class
?public class Scooter : IFactory
?{
?public void Drive(int miles)
?{
??Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
?}
?}
?/// A 'ConcreteProduct' class
?public class Bike : IFactory
?{
?public void Drive(int miles)
?{
?Console.WriteLine("Drive the Bike : " + miles.ToString() + "km");
?}
?}
?public abstract class VehicleFactory
?{
?public abstract IFactory GetVehicle(string Vehicle);
?}
?/// A 'ConcreteCreator' class
?public class ConcreteVehicleFactory : VehicleFactory
?{
?public override IFactory GetVehicle(string Vehicle)
?{
?switch (Vehicle)
?{
?case "Scooter":
?return new Scooter();
?case "Bike":
?return new Bike();
?default:
?throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
?}
?}
?}
?/// Factory Pattern Demo
?class Program
?{
?static void Main(string[] args)
?{
?VehicleFactory factory = new ConcreteVehicleFactory();
?IFactory scooter = factory.GetVehicle("Scooter");
?scooter.Drive(10);
?IFactory bike = factory.GetVehicle("Bike");
?bike.Drive(20);
?Console.ReadKey();
?}
?}
}}