Showing posts with label patterns. Show all posts
Showing posts with label patterns. Show all posts

Value Objects

0

Category :

It's often useful to represent things as a compound. A 2D coordinate consists of an x value and y value. An amount of money consists of a number and a currency. A date range consists of start and end dates, which themselves can be compounds of year, month, and day.

I run into the question of whether two compound objects are the same. Objects that are equal due to the value of their properties, in this case their x and y coordinates, are called value objects.

In some noon functional languages you will need to override the default equals method with the tests for the values.

One of the nice consequences of value objects is that I don't need to care about whether I have a reference to the same object in memory or a different reference with an equal value.

Aliasing Bug

To avoid aliasing bugs I follow a simple but important rule: value objects should be immutable. If I want to change my object, I create a new object instead. With objects I can usually do this by simply not providing any setting methods.


my thanks to:
https://martinfowler.com/bliki/ValueObject.html

Factory Method

0

Category : ,

The Factory completely hides/removes the process of creating objects from the client/caller.

Example

Lets say we have an eCommerce application and we have 2 payment gateways integrated with our application. Lets call these payment gateways BankOne and BankTwo.

Interface

We need a "Payment Gateway" interface to set the template/functionality that all payment gateways need to provide.

interface IPaymentGateway
{
    void MakePayment(Product product);        
}

Concrete implementations

Concrete implementations of Payment Gateways required:
public class BankOne : IPaymentGateway
{
    public void MakePayment(Product product)
    {
        // The bank specific API call to make the payment
        Console.WriteLine("Using bank1 to pay for {0}, amount {1}", product.Name, product.Price);
    }
}

public class BankTwo : IPaymentGateway
{
    public void MakePayment(Product product)
    {
        // The bank specific API call to make the payment
        Console.WriteLine("Using bank2 to pay for {0}, amount {1}", product.Name, product.Price);
    }
}
To be able to identify what payment mechanism has been selected, lets define a simple Enum PaymentMethod.
enum PaymentMethod
{
    BANK_ONE,
    BANK_TWO
}

Factory

Factory class to handle all the details of creating these objects.
public class PaymentGatewayFactory
{
    public virtual IPaymentGateway CreatePaymentGateway(PaymentMethod method, Product product)
    {
        IPaymentGateway gateway = null;

        switch(method)
        {
            case PaymentMethod.BANK_ONE:
                gateway = new BankOne();
                break;
            case PaymentMethod.BANK_TWO:
                gateway = new BankTwo();
                break;
        }

        return gateway;
    }
}
Our factory class accepts the selected payment gateway and then based on the selection it is creating the concrete payment gateway class. We have effectively abstracted out all these details from the client code. Otherwise every class that want to use a payment gateway would have to write all this logic.

Usage

Lets now look at how the client class can use this factory method to make the payment.
public class PaymentProcessor
{
    IPaymentGateway gateway = null;

    public void MakePayment(PaymentMethod method, Product product)
    {
        PaymentGatewayFactory factory = new PaymentGatewayFactory();
        this.gateway = factory.CreatePaymentGateway(method, product);

        this.gateway.MakePayment(product);
    }
}
Now our client class does not depend on the concrete payment gateway classes. It also does not have to worry about the creation logic of the concrete payment gateway classes. All this is nicely abstracted out in the factory class itself.


my thanks to the following article:
https://www.codeproject.com/Articles/874246/Understanding-and-Implementing-Factory-Pattern-i

Decorator Design Pattern Intro

0

Category : , ,

Decorator Design pattern allows developer to satisfy some SOLID rules:

  • 1) Single Responsibility Principle – Class/Function should do only one task or Class/Function should have only one reason to change.
  • 2) Open Close Principle – Class/Function is open for extension but close for modification.
  • 3) Liskov Substitution type – If type S is derived from Type T then object of Type T can be replaced by object of Type S.


Simple Example of Design Pattern

namespace BasicDecoratorPattern
{
    public class Client
    {
        public Client()
        {
            IBaseService realTimeService = new BasicServiceImplementaion();

            IBaseService basicRealTimeServiceDecorator1 = new Decorator1OnBasic(realTimeService);
            IBaseService basicRealTimeServiceDecorator2 = new Decorator2OnBasic(realTimeService);

            basicRealTimeServiceDecorator1.Print();
            basicRealTimeServiceDecorator2.Print();
        }
    }

    public interface IBaseService
    {
        void Print();
    }

    public class BasicServiceImplementaion : IBaseService
    {
        public void Print()
        {
            Console.WriteLine("Basic Item");
        }
    }

    public class Decorator1OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator1OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator ONE");
        }
    }

    public class Decorator2OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator2OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator SECOND");
        }
    }
}




my thanks to: http://www.codeproject.com/Articles/872818/How-and-Where-Decorator-Design-Pattern

Observer Pattern in .NET

0

Category :

a.k.a. Publisher-Subscriber Pattern.

Before .NET 4.0, we had to write custom code to implement Observer Pattern or use delegates and events. With the release of framework 4.0 came the IObservable and IObserver interfaces for implementing Observer Pattern.

Background

The Observer Pattern defines a one-to-many dependency between objects (Publisher and multiple Subscribers) so that when one object (Publisher) changes state, all the dependents (Subscriber) are notified and updated automatically.

Sample Scenario

The Code below is based on a scenario wherein we have a weather station which records weather data (temperature, humidity and pressure).

This data has to be consumed by multiple displays and displayed acordingly. Everytime there is new data available to the weather station it should "push" the data to the displays which should all be updated accordingly. Suppose we have 3 displays (Current Conditions, Statistics Display and Forecast Display), all of these have to be updated whenever new data is available at the Weather Station.

Technique #1 - Using Pure Object Oriented (OO) programming concepts.

Publisher
Weather Data Provider which provides the weather data, WeatherDataProvider Class implements the IPublisher interface as shown below:
public interface IPublisher
{
	// Registers a new subscriber on the list of subscribers it has to 
    // notify whenever WeatherData has changed
    void RegisterSubscriber(ISubscriber subscriber);

    // Removes a registered subscriber from the publisher's notification list
    void RemoveSubscriber(ISubscriber subscriber);

    // This method actually invokes a method on the subscriber object to
    // notify that some new WeatherData is available
    void NotifySubscribers();
}
The concrete implementaion of a WeatherDataProvider would be as below:
public class WeatherDataProvider : IPublisher
{
    List ListOfSubscribers;
    WeatherData data;
    public WeatherDataProvider()
    {
        ListOfSubscribers = new List();
    }
    public void RegisterSubscriber(ISubscriber subscriber)
    {
        ListOfSubscribers.Add(subscriber);
    }

    public void RemoveSubscriber(ISubscriber subscriber)
    {
        ListOfSubscribers.Remove(subscriber);
    }

    public void NotifySubscribers()
    {
        foreach (var sub in ListOfSubscribers)
        {
            sub.Update(data);
        }
    }

    private void MeasurementsChanged()
    {
        NotifySubscribers();
    }
    public void SetMeasurements(float temp, float humid, float pres)
    {
        data = new WeatherData(temp, humid, pres);           
        MeasurementsChanged();
    }
}

Subscriber

The subscribers here are actually the weather displays, which consume the data. Each subcsriber should implement the ISubscriber interface.
public interface ISubscriber
{
    void Update(WeatherData data);
}
An implementation of the CurrentConditionsDisplay is as under.
public class CurrentConditionsDisplay : ISubscriber
{
    WeatherData data;
    IPublisher weatherData;

    public CurrentConditionsDisplay(IPublisher weatherDataProvider)
    {
        weatherData = weatherDataProvider;
        weatherData.RegisterSubscriber(this);
    }

    public void Display()
    {
        Console.WriteLine("Current Conditions : Temp = {0}Deg | Humidity = {1}% | Pressure = {2}bar", data.Temperature, data.Humidity, data.Pressure);
    }
   
    public void Update(WeatherData data)
    {
        this.data = data;
        Display();
    }
}
Above we have injected the IPublisher interface via the Constructor.
When the display in instantiated it makes a call to the RegisterSubscriber method of the WeatherDataProvider and registers itself as an interested subscriber.
If a display wants to unregister itself, it has to call the RemoveSubscriber method of the WeatherDataProvider.

Technique #3 - Using IObservable and IObserver.

In the generic Type IObservable and IObserver, the T in our case would be WeatherData.

Publisher

The publisher (WeatherDataProvider) has to just implement the IObservable interface (below).
public class WeatherDataProvider : IObservable
    {
        List> observers;

        public WeatherDataProvider()
        {
            observers = new List>();
        }

        public IDisposable Subscribe(IObserver observer)
        {
            if (!observers.Contains(observer))
            {
                observers.Add(observer);
            }
            return new UnSubscriber(observers, observer);
        }

        private class UnSubscriber : IDisposable
        {
            private List> lstObservers;
            private IObserver observer;

            public UnSubscriber(List> ObserversCollection, IObserver observer)
            {
                this.lstObservers = ObserversCollection;
                this.observer = observer;
            }

            public void Dispose()
            {
                if (this.observer != null)
                {
                    lstObservers.Remove(this.observer);
                }
            }
        }

        private void MeasurementsChanged(float temp, float humid, float pres)
        {
            foreach (var obs in observers)
            {
                obs.OnNext(new WeatherData(temp, humid, pres));
            }
        }

        public void SetMeasurements(float temp, float humid, float pres)
        {
            MeasurementsChanged(temp, humid, pres);
        }
    }
Observers register to receive notifications by calling its IObservable.Subscribe method, which assigns a reference to the observer object to a private generic List object. The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. The Unsubscriber class is simple a nested class that implements IDisposable and also keeps a list of Subscribed users and is used by the observers (Displays in our case), to unsubscribe.

Also, there is a function OnNext which we have invoked on the subscriber/observer. This function is actually an inbuilt function of IObserver which indicates that something has changed in the collection. This is actually the function which notifies the subscribers of changes.

Subscriber

The subscriber (Displays) have to just implement the IObserver interface. The implementation of the CurrentConditionsDisplay is as under. We can have similarly any number of displays.
public class CurrentConditionsDisplay : IObserver
{
    WeatherData data;
    private IDisposable unsubscriber;

    public CurrentConditionsDisplay()
    {

    }
    public CurrentConditionsDisplay(IObservable provider)
    {
        unsubscriber = provider.Subscribe(this);
    }
    public void Display()
    {
        Console.WriteLine("Current Conditions : Temp = {0}Deg | 
                            Humidity = {1}% | Pressure = {2}bar", 
                            data.Temperature, data.Humidity, data.Pressure);
    }

    public void Subscribe(IObservable provider)
    {
        if (unsubscriber == null)
        {
            unsubscriber = provider.Subscribe(this);
        }
    }

    public void Unsubscribe()
    {
        unsubscriber.Dispose();
    }

    // Pass the observer a T object that has current data, changed data, or fresh data.
    public void OnNext(WeatherData value)
    {
        this.data = value;
        Display();
    }

    // Notify the observer that some error condition has occurred
    public void OnError(Exception error)
    {
        Console.WriteLine("Some error has occurred..");
    }

    // Notify the observer that it has finished sending notifications
    public void OnCompleted()
    {
        Console.WriteLine("Additional temperature data will not be transmitted.");
    }
}

my thanks to:
http://www.codeproject.com/Articles/796075/Implement-Observer-Pattern-in-NET-techniques

Design Pattern - Unit of Work

0

Category :

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
http://martinfowler.com/eaaCatalog/unitOfWork.html

Basically unit of work is transaction management. Within one transaction, we may pull data from database, make some changes, add new record, etc.

There are some important notes about unit of work and web application:
1. Unit of work should be unique for each request, i.e. unit of work cannot share between requests.
2. Unit of work should be share within one request, i.e. if you use unit of work from your controller and other places, that unit of work object should be the same if it is within one request.

Dependency Injection comes to rescue to make sure the above requirements are met. Dependency Injection provides life time management and resolving the dependencies. For our case, unit of work object's life time must be per request.

http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/



my thanks to: http://jittuu.com/2012/2/9/UnitOfWork-pattern-and-asp.net-mvc/

Gang of Four Design Patterns

0

Category : , ,

What are Design Patterns?

Design patterns provide solutions to common software design problems. In the case of object-oriented programming, design patterns are generally aimed at solving the problems of object generation and interaction, rather than the larger scale problems of overall software architecture. They give generalised solutions in the form of templates that may be applied to real-world problems.

Design patterns are a powerful tool for software developers. However, they should not be seen as prescriptive specifications for software. It is more important to understand the concepts that design patterns describe, rather than memorising their exact classes, methods and properties. It is also important to apply patterns appropriately. Using the incorrect pattern for a situation or applying a design pattern to a trivial solution can overcomplicate your code and lead to maintainability issues.


Creational Patterns

The first type of design pattern is the creational pattern. Creational patterns provide ways to instantiate single objects or groups of related objects. There are five such patterns:

Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Builder. The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Factory Method. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Prototype. The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Singleton. The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.


Structural Patterns

The second type of design pattern is the structural pattern. Structural patterns provide a manner to define relationships between classes or objects.

Adapter. The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Bridge. The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Composite. The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.

Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex models containing many hundreds, thousands or hundreds of thousands of similar objects.

Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary.

Behavioural Patterns

The final type of design pattern is the behavioural pattern. Behavioural patterns define manners of communication between classes and objects.

Chain of Responsibility. The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
Command. The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Interpreter. The interpreter pattern is used to define the grammar for instructions that form part of a language or notation, whilst allowing the grammar to be easily extended.

Iterator. The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Mediator. The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
Memento. The memento pattern is used to 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.

Observer. The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

State. The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Strategy. The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Template Method.
The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed.

Visitor. The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.


my thanks to:
http://www.blackwasp.co.uk/GofPatterns.aspx