Adapter pattern: Design Pattern Series – Part: 13

Adapter Pattern falls under Structural pattern:

According to the GoF, the intent of the Adapter pattern is,

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces

Problem: 
Sometimes a toolkit or class library can not be used because its interface is  incompatible with the interface required by an application and We can not change the library interface,  since we may not have its source code. For example the below example uses the grid which have the Method called Fill. But lets say  at some point of time you might like to use Infragistics grid(3rd party) which is not having the method called “Fill”, for example, and you may not populate the Client object with the Infragistics grid because of this incompatibility.

Solution:
The solution is to create an InfragisticsAdapter(Who Adapts the adaptee to client – pattern) which composes the Adaptee(Infragistics) and the InfragisticsAdapter will be compatible with the existing interface so that the client can be populated with Adapter.

Please find below the UML for this pattern:

adpater

The UML class diagram above describes an implementation of the adapter design pattern. The items in the diagram are described below:

 Client: The client class is that which requires the use of an incompatible type. It expects to interact with a type that implements the ITarget interface. However, the class that we wish it to use is the incompatible Adaptee.
 ITarget: This is the expected interface for the client class. Although shown in the diagram as an interface, it may be a class that the adapter inherits. If a class is used, the adapter must override its members.
 Adaptee: This class contains the functionality that is required by the client. However, its interface is not compatible with that which is expected.
 Adapter: This class provides the link between the incompatible Client and Adaptee classes. The adapter implements the ITarget interface and contains a private instance of the Adaptee class. When the client executes MethodA on the ITarget interface, MethodA in the adapter translates this request to a call to MethodB on the internal Adaptee instance.

Example:

public class Client
{
   
    public Client(IGrid  iGrid)
    {
        this.iGrid = iGrid;
 } 
 private IGrid iGrid;
 
    public void PopulateGrid(DataSet ds)
    {
        iGrid.Fill(ds);
    }
}
 
 
public interface IGrid
{
    void Fill(DataSet ds);
}
 
 
public class Infragistics
{
    public void DataFill(DataSet ds)
    {
        // fill the data into grid.
    }
}

public class InfragisticsAdapter : IGrid
{
    Infragistics _adaptee = new Infragistics();
 
    public void Fill(DataSet ds)
    {
        _adaptee.DataFill(ds);
    }
}

public void static Main()
{
 var client = new Client(new InfragisticsAdapter());
 var ds = GetDataset();
 client.PopulateGrid(ds); //– Hurray it will now work.
}

Rules of thumb
* Adapter makes things work after they’re designed; Bridge makes them work before they are.
* Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to   make unrelated classes work together.
* Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced   interface.
* Adapter is meant to change the interface of an existing object. Decorator enhances another object without changing its   interface. Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports   recursive composition, which isn’t possible with pure Adapters.
* Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing   interfaces work together as opposed to defining an entirely new one.

 

Proxy pattern: Design Pattern Series – Part: 12

Proxy Pattern falls under Structural pattern:

According to the GoF, the intent of the Proxy pattern is,

 Provide a surrogate or placeholder for another object to control access to it.

Problem:
 You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are  actually requested by the client.

Solution:

 A Proxy can also be defined as a surrogate. In the real work a cheque or debit card is a proxy for what is in our bank account.  It can be used in place of cash, which is what is needed, and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does – controls and manage access to the object they are “protecting”.

Please find below the UML for this pattern:

proxy

The participants classes in the proxy pattern are:

Subject – Interface implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.

Proxy – Maintains a reference that allows the Proxy to access the RealSubject.
Implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject.
Controls access to the RealSubject and may be responsible for its creation and deletion.
Other responsibilities depend on the kind of proxy.

RealSubject – the real object that the proxy represents.

 

Example :

public interface Image {    // Subject Interface

 void showImage();
 
}

public class ImageProxy : Image { // Proxy Subject

 private String imageFilePath;
 
 private Image proxifiedImage;
 
 
 public ImageProxy(String imageFilePath) {
  this.imageFilePath= imageFilePath; 
 }
  
 public void showImage() {

  proxifiedImage = new HighResolutionImage(imageFilePath);
  
  // now call showImage on realSubject
  proxifiedImage.showImage();
  
 } }

public class HighResolutionImage : Image { // Real Subject

 public HighResolutionImage(String imageFilePath) {
  
  loadImage(imageFilePath);
 }

 private void loadImage(String imageFilePath) {

  // load Image from disk into memory
  // this is heavy and costly operation
 }

 
 public void showImage() {

  // Actual Image rendering logic

 } }

Rules of thumb:
* Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced  interface.
* Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection  to another object, and the implementations keep a reference to the object to which they forward requests.

 

Abstract Factory pattern: Design Pattern Series – Part: 11

Abstract Factory falls under Creational Pattern:

According to the GoF, the intent of the Abstract Factory pattern is,

 Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Problem:
You have seen a factory method already. But in the real world, factory class will not be one and it could be many to produce appropriate family of objects. Lets say, In a car company, a particular factory can be used to create different doors (front, back, side., ) , for example DoorFactory. The same goes to different lights, seats etc., So here what we have is group of factories. The problem here is sometimes we need to create a particular factory among group of factories.
 

Solution:

So we abstract out factories and at runtime we are going to create desired concrete factory.

Please find below the UML for this pattern:

abstract

The classes and/or objects participating in this pattern are:

•AbstractFactory  (AnimalFactory) declares an interface for operations that create abstract products

•ConcreteFactory   (SeaFactory, LandFactory) implements the operations to create concrete product objects

•AbstractProduct   (Animal) declares an interface for a type of product object

•Product  (Lion, Fish) defines a product object to be created by the corresponding concrete factory
 implements the AbstractProduct interface

•Client  (AnimalWorld) uses interfaces declared by AbstractFactory and AbstractProduct classes

Example :

public interface AnimalFactory { // Abstrct Factory
  Animal createAnimal(string condition);
}

 public class SeaFactory : AnimalFactory { // Concrete Factory
   public Animal createAnimal(string condition) {

     if(condition == “S”)
       return new Shark();
     return new Fish();
  } 
}

public class LandFactory : AnimalFactory { // Concrete Factory

  public Animal createAnimal(string condition) {
     if(condition == “E”)
       return new Elephant();
     return new Lion();
  }
}

public class AnimalWorld
{
 public AnimalFactory GetAnimalFactory(string condition)
 {
    if(condition == “Land”)
       return new LandFactory ();
     return SeaFactory();
 }
}

Factory Method Pattern : Design Pattern Series – Part: 10

Factory Method Pattern falls under Creational pattern:

Intent :

* Defines an interface for creating objects, but let subclasses to decide which class to instantiate
* Refers to the newly created object through a common interface

Problem:

* At run time based on user input or by measuring some other application characteristics, you might have to create an object but with out having too much of condition logics in business code.
* You might like to separate the creation code from code that does business and you may be the fan of Single Responsibility Principle.

Solution:

The Factory Method Design Pattern allows you to create objects without being bothered on what is the actual class being created. The benefit is that the client code (calling code) can just say “give me an object that can do XYZ” without knowing what is the actual class that can do “XYZ”.

So all you do is separate the object creation logic from business code and send it to the factory and your business code says to factory or signals your desire to factory and factory produce suitable object for you.

Find below the UML for this pattern:Factory method

Example:

interface Product
{
void GetDetails();
}

class DentalProduct: Product
{
public void GetDetails()
{
Console.WriteLine(“DentalProduct Details are Called”);
}
}

class VisionProduct : Product
{
public void GetDetails()
{
Console.WriteLine(“VisionProduct Details are called”);
}
}

class ProductFactory
{
public static Product GetProduct(string prod)
{
if(prod==”V”)
return new VisionProduct();
return new DentalProduct();
}
}

Client:

Product p = ProductFactory.GetProduct(“V”);

Iterator Pattern : Design Pattern Series – Part: 9

Iterator pattern falls under Behavioral Pattern.

Intent :

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Problem :

Whenever I work with a collection object, I might try to get first/last element or iterate all the element in the collection object. But what important here is that I do not want to know what kind of collection I am working with but the collection object should allow me to iterate/access it in a same way as like other collection object. For example, doing foreach in all the collection object.

Solution :

We can solve our problem simply by not caring much about collection implementation but rather we might facilitate the iteration by having the common pattern. We should have a mechanism to traverse in the same way a list or an array. It doesn’t matter how they are internally represented. That mechanism is called Iterator Pattern.

The .NET Framework and C# language has the Iterator pattern embedded deep in its code. The IEnumerable interface is in fact the facilitator of the Iterator pattern. Generics and Collection classes in C# can be iterated through an enumerator which is in fact an Iterator pattern implementation.

Find below the UML of Iterator pattern:Iterator

Example :

// Iterator pattern — Structural example

using System;
using System.Collections;

namespace DoFactory.GangOfFour.Iterator.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Iterator Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
ConcreteAggregate a = new ConcreteAggregate();
a[0] = “Item A”;
a[1] = “Item B”;
a[2] = “Item C”;
a[3] = “Item D”;

// Create Iterator and provide aggregate
ConcreteIterator i = new ConcreteIterator(a);

Console.WriteLine(“Iterating over collection:”);

object item = i.First();
while (item != null)
{
Console.WriteLine(item);
item = i.Next();
}

// Wait for user
Console.ReadKey();
}
}

/// <summary>
/// The ‘Aggregate’ abstract class
/// </summary>
abstract class Aggregate
{
public abstract Iterator CreateIterator();
}

/// <summary>
/// The ‘ConcreteAggregate’ class
/// </summary>
class ConcreteAggregate : Aggregate
{
private ArrayList _items = new ArrayList();

public override Iterator CreateIterator()
{
return new ConcreteIterator(this);
}

// Gets item count
public int Count
{
get { return _items.Count; }
}

// Indexer
public object this[int index]
{
get { return _items[index]; }
set { _items.Insert(index, value); }
}
}

/// <summary>
/// The ‘Iterator’ abstract class
/// </summary>
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}

/// <summary>
/// The ‘ConcreteIterator’ class
/// </summary>
class ConcreteIterator : Iterator
{
private ConcreteAggregate _aggregate;
private int _current = 0;

// Constructor
public ConcreteIterator(ConcreteAggregate aggregate)
{
this._aggregate = aggregate;
}

// Gets first iteration item
public override object First()
{
return _aggregate[0];
}

// Gets next iteration item
public override object Next()
{
object ret = null;
if (_current < _aggregate.Count – 1)
{
ret = _aggregate[++_current];
}

return ret;
}

// Gets current iteration item
public override object CurrentItem()
{
return _aggregate[_current];
}

// Gets whether iterations are complete
public override bool IsDone()
{
return _current >= _aggregate.Count;
}
}
}

Singleton Pattern : Design Pattern Series – Part: 8

Singleton Design Pattern falls under Creational Pattern.

Intent
 ◦Ensure a class has only one instance, and provide a global point of access to it.
 ◦Encapsulated “just-in-time initialization” or “initialization on first use”.

Problem

 Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.

Solution

The motivation is that some real-world objects should have no more than one instance. For example, most computers have only one audio output. No more than one sound can be played at a time. Therefore a class that represents the computer’s audio device should have exactly one instance.

If there were two audio device objects, programmers could try to play multiple sounds simultaneously, generally with unpredictable and unwanted results. If there is only one audio device object, it can implement internal queuing as necessary to make sure that one sound file stops or finishes before it tries to play another. A queue could be shared between different audio device objects, but the overhead for maintaining the queue and communicating between the different objects is prohibitive.
Furthermore, since there is only one audio device to start with, that device might as well be set up as soon as the class is loaded. Initialization is simpler because you only have to do it once for the single instance of the AudioDevice class, rather than repeatedly for different instances.

Access to the singleton is controlled via the static method Instance. It is most often the case that the singleton should also be globally accessible, and this is achieved by making the creation method public. However, unlike the scenario in which a global variable is instantiated as the singleton, this pattern prevents creation of any additional instances, while simultaneously allowing global access. Note that the class constructor is private—there is no way to circumvent the static method and directly create an instance of the class.

There are additional benefits, that is the creation of the singleton can be delayed until it is actually needed. A variable declared at global scope will be created on startup regardless of whether it is needed—it may very well be that the object isn’t always needed. C# doesn’t allow variables at global scope anyway, but it is possible to create an object on the heap at the outset of a method and not use it until much later, if at all. The Singleton pattern offers an elegant solution in such cases.

Find below the UML of the singleton pattern.Singleton

Applicability & Examples
According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 – Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 – Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 – Accesing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let’s say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to manage all the operations on the serial port.

Example 4 – Factories implemented as Singletons

Let’s assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Code Example:

using System;

public class MySingleton
{
   private static MySingleton instance;

   private MySingleton() {}

   public static MySingleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new MySingleton();
         }
         return instance;
      }
   }
}

Thread, ThreadPool and Task – A highlevel Intro.

Thread

Threads are an operating system feature that lets application logic be separated into several concurrent execution paths. This feature is useful when complex applications have many tasks that can be performed at the same time.

When an operating system executes an instance of an application, it creates a unit called a process to manage the instance. The process has a thread of execution. This is the series of programming instructions performed by the application code. For example, if a simple application has a single set of instructions that can be performed serially, there is just one execution path or thread through the application. More complex applications may have several tasks that can be performed in tandem, instead of serially. The application can do this by starting separate processes for each task. However, starting a process is a resource-intensive operation. Instead, an application can start separate threads. These are relatively less resource-intensive. Additionally, each thread can be scheduled for execution independently from the other threads associated with a process.

Threads allow complex applications to make more effective use of a CPU, even on computers that have a single CPU. With one CPU, only one thread can execute at a time. If one thread executes a long-running operation that does not use the CPU, such as a disk read or write, another one of the threads can execute until the first operation is completed. By being able to execute threads while other threads are waiting for an operation to be completed, an application can maximize its use of the CPU. This is especially true for multi-user, disk I/O intensive applications such as a database server. Computers that have multiple microprocessors or CPUs can execute one thread per CPU at the same time. For example, if a computer has eight CPUs, it can execute eight threads at the same time.

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can’t set anything else. You can’t even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

Task

A task is a lightweight object for managing a parallelizable unit of work. A task avoids the overhead of starting a dedicated thread by using the CLR’s thread pool: this is the same thread pool used by ThreadPool.QueueUserWorkItem, but in CLR 4.0 it is enhanced to work more efficiently with Tasks.

Tasks can be used whenever you want to execute something in parallel; in CLR 3.0 / 3.5 we would have used the ThreadPool for this. However, the advantage of tasks is that they are tuned for leveraging multicores, unlike the ThreadPool by itself. In fact, the Parallel class and PLINQ are internally built on the task parallelism constructs.

A question answerd by Eric Lippert in Stack Overflow :

Q: what is diffrence between a Task and a Thread?

A: Suppose you are running a book delivery company. You have four cars and four drivers. A car is a thread, a driver is a processor, and a book delivery is a task. The problem you face is how to efficiently schedule the drivers and cars so that the tasks get done as quickly as possible.

Where things get weird is when there are more cars (threads) than drivers (processors). What happens then is halfway through a trip the driver parks one car (suspends the thread) and gets into a different car (switches context), drives that one around for a while performing tasks, and then eventually comes back to the first car. Obviously that is not as efficient as one driver staying in one car.

The idea of task-based parallism is to break up the work into small tasks that can produce results in the future, and then efficiently allocate exactly as many threads as there are processors so that you don’t waste time context switching. In practice, it usually does not work out that nicely, but that’s the idea.

which one is better, task or thread?

The question cannot be answered because it doesn’t make any sense. Which is better, a book to deliver to a customer, or a car to deliver it in? A car is a device that can be used to deliver a book; those two things are not things you can sensibly describe as “better” or “worse” than the other. It’s like asking “which is better, a hole or a drill?”

Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

Follow

Get every new post delivered to your Inbox.