Pages: Prev 1 2 3 4 5 6 7 Next
– page 5

Agile & Lean Software Development Management

deep thoughts on doing real work

The Visitor pattern uses an external class to act on data in other classes. This is a useful approach to you when you have a polymorphic operation that cannot reside in the class hierarchy. Visitor is also a useful way to extend the behavior of a class hierarchy without the need to alter existing classes or to implement the new behavior in every subclass that requires it.

image

I think the visitor pattern feels a bit of a weird pattern. I mean weird in a way that it feels not very object-oriented nor structured way of programming. On the other hand, sometimes you have a collection of similar classes which differ in one or more methods. If you don’t want to ‘pollute’ your object-oriented hierarchy with these class-specific methods, then you can use the visitor pattern.

All the client needs is an object structure, a visitor and an element. One or more elements are attached to the object structure. The visitor visits the object structure and does ‘something’ with the attached elements.

class Client
{
    static void Main()
    {
        ObjectStructure objectstructure = new ObjectStructure();
        Element element = new ConcreteElement();
        objectstructure.Attach(element);
        ConcreteVisitor visitor = new ConcreteVisitor();
        objectstructure.Accept(visitor);
        Console.ReadKey();

    }
}

The abstract class Visitor can have one or more concrete implementations, which do their work on the attached elements.

abstract class Visitor
{
    public abstract void VisitConcreteElement(ConcreteElement concreteElement);
}

class ConcreteVisitor : Visitor
{
    public override void VisitConcreteElement(ConcreteElement concreteElement)
    {
         Console.WriteLine("{0} visited by {1}", concreteElement.GetType().Name,          this.GetType().Name);
    }
}

The element class accepts a visitor and propagates an operation towards this visitor.

abstract class Element
{
    public abstract void Accept(Visitor visitor);
}

class ConcreteElement : Element
{
    public override void Accept(Visitor visitor)
    {
        visitor.VisitConcreteElement(this);
    }

    public void Operation()
    {
    }
}

The object structure contains all machinery needed for maintenance of a list of attached elements. In this way it resembles the subject class of the observer pattern.

class ObjectStructure
{
    private List m_Elements = new List();
    public void Attach(Element element)
    {
        m_Elements.Add(element);
    }
    public void Detach(Element element)
    {
        m_Elements.Remove(element);
    }
    public void Accept(Visitor visitor)
    {
        foreach (Element element in m_Elements)
        {
            element.Accept(visitor);
        }
    }
}

By now you should get some idea how the visitor pattern works.

Handy? I am not sure, I never used it in real life. What do you think. Please let me know.

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Observer pattern is intended to provide you with a means to present data in several different forms at once so that when one object changes state, all its dependents are notified and updated automatically.

observer-pattern

The Observer pattern can be found everywhere. Mostly it is used when you have more than one view on the same data. For example, a list view and a detail view.

In the client, a couple of observers are attached to their subject of interest. As soon as the state of the subject changes, all observers are notified that there is a change of state.

class Client
{
    static void Main()
    {
        ConcreteSubject subject = new ConcreteSubject();

        ConcreteObserver observer1 = new ConcreteObserver(subject, "A");
        subject.Attach(observer1);

        ConcreteObserver observer2 = new ConcreteObserver(subject, "B");
        subject.Attach(observer2);

        subject.SubjectState = "NEW_SUBJECT_STATE";
        subject.Notify();

        Console.ReadKey();
    }
}

The abstract parent class Subject contains a list of observers and methods necessary for attaching and detaching observers. Most important method is notify which traverses the list and notifies all attached observers.

abstract class Subject
{
    private List m_Observers = new List();
    public void Attach(Observer observer)
    {
        m_Observers.Add(observer);

    }
    public void Detach(Observer observer)
    {
        m_Observers.Remove(observer);

    }
    public void Notify()
    {
        foreach (Observer o in m_Observers)
        {
               o.Update();
         }
    }
}

The concrete child class contains a certain state, which can be virtually anything. In this example, something simple. Just a string containing im-por-tant information.

class ConcreteSubject : Subject
{
    public string SubjectState { get; set; }
}

All observers need some way to update their state when they are notified. This is done by implementing the Update method of abstract class Observer.

abstract class Observer
{
    public abstract void Update();
}

The concrete observer implements the abstract update method, plus its own methods.

class ConcreteObserver : Observer
{
    private string m_Name;
    private string m_ObserverState;

    public ConcreteObserver(ConcreteSubject subject, string name)
    {
        this.Subject = subject;
        this.m_Name = name;
    }

    public override void Update()
    {
        m_ObserverState = Subject.SubjectState;
        Console.WriteLine("Observer {0}'s new state is {1}", m_Name, m_ObserverState);
    }

    public ConcreteSubject Subject { get; set; }
}

When you think about the problem this pattern solves, you probably agree with me that this is a relatively simple but powerful pattern.

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Builder pattern is used to separate the construction of complex objects from their representation so the construction process can be used to create different representations. The construction logic is isolated from the actual steps used to create the complex object.

image

What I like about the builder pattern is that it cloacks the actual construction of objects in a way that they seem to fit seamlessly in the same high-level structure. Sounds a bit difficult, but really isn’t. With the builder pattern the user is given the choice to create the type of object he wants but the construction process is still the same.

Let’s look at an example. Imagine that the client wants to show product data in different ways. To accomplish different representations, different builders are needed. The Director class directs the construction into a Product.

public class Client
{
    public static void Main()
    {
        Director director = new Director();

        Builder firstBuilder = new FirstConcreteBuilder();
        Builder secondBuilder = new SecondConcreteBuilder();

        director.Construct(firstBuilder);

        Product product = firstBuilder.GetResult();
        product.Show();

        director.Construct(secondBuilder);
        product = secondBuilder.GetResult();
        product.Show();

        Console.ReadKey();
    }
}

As you can see Product and Director remain the same for both constructions. So, the difference really lies in the construction process itself. And that is the real power of the builder pattern.

The Director directs the high-level construction process of parts, first build the first part then the next part.

class Director
{
    public void Construct(Builder builder)
    {
        builder.BuildFirstPart();
        builder.BuildSecondPart();
    }
}

The abstract class Builder defines the abstract methods necessary for constructing the object and getting the result.

abstract class Builder
{
    public abstract void BuildFirstPart();
    public abstract void BuildSecondPart();
    public abstract Product GetResult();
}

The concrete classes implement the construction methods.

class FirstConcreteBuilder : Builder
{
    private Product m_Product = new Product();
    public override void BuildFirstPart()
    {
        m_Product.Add("First Part");
    }

    public override void BuildSecondPart()
    {
        m_Product.Add("Second Part");
    }

    public override Product GetResult()
    {
        return m_Product;
    }
}

class SecondConcreteBuilder : Builder
{
    private Product m_Product = new Product();

    public override void BuildFirstPart()
    {
        m_Product.Add("Another First Part");
    }

    public override void BuildSecondPart()
    {
        m_Product.Add("Another Second Part");
    }

    public override Product GetResult()
    {
        return m_Product;
    }
}

Finally, the product is the resulting product of construction. Of course, this is a simple example but this pattern comes in handy when you are in the situation of complex construction of products.

class Product
{
    private List m_Parts = new List();
    public void Add(string part)
    {
        m_Parts.Add(part);
    }

    public void Show()
    {
        Console.WriteLine("Product consists of the following parts:");

        foreach (string part in m_Parts)
        {
            Console.WriteLine("- " + part);
        }
    }
}

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Mediator pattern is intended to define an object that encapsulates how a set of objects interacts. Object do not communicate directly with eachother, but through a mediator. This reduces the dependencies between communicating objects.

image

The client instantiates the communicating objects, so called colleagues, and a mediator through which they are communicating.

Colleague c1 = new ConcreteColleague1(m);
Colleague c2 = new ConcreteColleague2(m);

Mediator m = new ConcreteMediator();

m.AddColleague(c1);
m.AddColleague(c2);

c1.Send(c2, "Hello, c2. Are you there?");
c2.Send(c1, "No, goodbye!");

The abstract class Colleague contains a Mediator, which is injected at instantiation. In this example, it has two methods for communication. One for sending a message, the other for receiving a message.

abstract class Colleague
{
    protected Mediator mediator;

    public Colleague(Mediator mediator)
    {
        this.mediator = mediator;
    }

    abstract public void Send(Colleague to, string message);
    abstract public void Received(Colleague from, string message);
}

The abstract class Mediator contains an internal store for colleages and a method for adding colleagues. It also contains an abstract method for sending a message to the preferred colleague.

abstract class Mediator
{
    protected List colleagues = new List();

    public void AddColleague(Colleague colleague)
    {
        colleagues.Add(colleague);
    }

    public abstract void Send(Colleague colleague, string message);
}

The concrete class implements the abstract method. In this case, it forwards the message to the selected colleague.

class ConcreteMediator : Mediator
{
        public override void Send(Colleague to, string message)
        {
            to.Received(to,message);
        }
 }

Finally, the selected concrete colleague receives the message. I only show the concrete class ConcreteColleague1, since ConcreteColleague2 is almost identical to this one. So if you want to try this code, I suggest you do a search and replace on ConcreteColleague1.

class ConcreteColleague1 : Colleague
{
    public ConcreteColleague1(Mediator mediator)
    : base(mediator) { }

    override public void Send(Colleague to, string message)
    {
        Console.WriteLine("Sending message (ConcreteColleague1)-----------------------------");
        Console.WriteLine("To : " + to.GetType().Name);
        Console.WriteLine("Message: " + message);
        Console.WriteLine();

        mediator.Send(to,message);
    }

    override public void Received(Colleague from, string message)
    {
        Console.WriteLine("Receiving message (ConcreteColleague1)---------------------------");
        Console.WriteLine("From : " + from.GetType().Name);
        Console.WriteLine("Message: " + message);
        Console.WriteLine();
    }
}

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Flyweight pattern is intended to use sharing to support large numbers of fine-grained objects more efficiently and reduce resource usage. The Flyweight pattern is especially useful when there is a need of many, many similar objects.

image

When I hear flyweight, I instantly think about characters in words, sentences, and stories. If a character is a flyweight, then there certainly are a lot of similar objects within text. Information the characters probably share is font size, color, font family and other things.

The client contains the information that is shared between all flyweights, except the unshared flyweight. It uses a factory method pattern to create a large number of flyweights. Next, each object performs a similar action on provided the information.

string information = "shared info";

FlyweightFactory factory = new FlyweightFactory();

for (int i = 0; i < 5; i++)
{
    string key = i.ToString();
    Flyweight f = factory.GetFlyweight(key);
    f.Operation(key, information);
}

UnsharedConcreteFlyweight unsharedFlyweight = new UnsharedConcreteFlyweight();
unsharedFlyweight.Operation("-", information);

The flyweight factory creates flyweights and puts them in a hash table. The method GetFlyweigth gets the flyweight from the hash table by its key. In this way each flyweight is created only once. The factory also could use a singleton pattern for object creation.

class FlyweightFactory
{
    private Hashtable flyweights = new Hashtable();
    public FlyweightFactory()
    {
        for (int i = 0; i < 5; i++)
        {
            string key = i.ToString();
            flyweights.Add(key, new ConcreteFlyweight());
        }
    }

    public Flyweight GetFlyweight(string key)
    {
        return ((Flyweight)flyweights[key]);
    }
}

The flyweights inherit from an abstract base class. The same holds true for the unshared flyweight, it only has a different implementation of the operation.

abstract class Flyweight
{
    public abstract void Operation(string key, string information);
}

class ConcreteFlyweight : Flyweight
{
    public override void Operation(string key, string information)
    {
        Console.WriteLine(string.Format("Flyweight {0}: {1}", key, information));
    }
}

class UnsharedConcreteFlyweight : Flyweight
{
    public override void Operation(string key, string information)
    {
        Console.WriteLine(string.Format("Unshared {0}: {1}", key, information));
    }
}

So far, so good. To see this pattern working, we need a real world example. How about some bouncing balls? To be continued….

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The iterator pattern provides a client with a way to access the elements of an aggregate object sequentially without having to know the underlying representation. The iterator is especially useful because it provides the client with a common interface so it doesn’t need to know anything about the underlying data structure.

image

If you want to loop through an collection of elements, the iterator pattern comes in very handy. In this example the client first fills an aggregate object with string elements. Next, an iterator is instantiated with the collection. Last, the iteration is done. The fun part is that you can change the implementations of underlying data and iterator without having to change the client.

Aggregate aggregate = new ConcreteAggregate();
for (int i = 0; i < 5; i++)
{
    aggregate[i] = string.Format("listitem {0}", i);
}
Iterator iterator = new ConcreteIterator(aggregate);
Console.WriteLine("Items in list:\n");
object item = iterator.First();
 while (item != null)
{
    Console.WriteLine(item);
    item = iterator.Next();
 }

The abstract aggregate class its most important abstract method is CreateIterator. For convenience of this example, an indexer and a property Count are also defined. The concrete aggregate object is just a wrapper around an ordinary ArrayList.

abstract class Aggregate
{
    public abstract object this[int i] { get; set; }
    public abstract int Count { get; }
    public abstract Iterator CreateIterator();
}

class ConcreteAggregate : Aggregate
{
    private ArrayList m_Items = new ArrayList();
    public override Iterator CreateIterator()
    {
        return new ConcreteIterator(this);

    }
    public override int Count
    {
        get
        {
            return m_Items.Count;

        }
    }
    public override object this[int index]
    {
        get
        {
            return m_Items[index];

        }
        set
        {
            m_Items.Insert(index, value);

        }
    }
}

The iterator does the looping work. First, an aggregate object is injected into the iterator upon instantiation. The rest of the code is just implementation of all abstract members.

class ConcreteIterator : Iterator
{
    private Aggregate m_Aggregate;
    private int m_Index = 0;

    public ConcreteIterator(Aggregate aggregate)
    {
        this.m_Aggregate = aggregate;
    }

    public override object First()
    {
        return m_Aggregate[0];
    }

    public override object Next()
    {
        object result = null;
        if (m_Index < m_Aggregate.Count - 1)
        {
            result = m_Aggregate[++m_Index];
        }
        return result;
    }

    public override object CurrentItem()
    {
        return m_Aggregate[m_Index];
    }

    public override bool IsDone()
    {
        return m_Index >= m_Aggregate.Count;
    }
}

Knowing this, can you imagine a real world situation when to use this pattern? This is such an important pattern, that it is a built-in pattern in C#. If you want read more about use of this pattern, read Using the Iterator Pattern in C# ASP .NET, by Kory Becker

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Bridge pattern is intended to decouple an abstraction from its implementation so both can vary independently.

image

The bridge pattern is especially useful when you are in need of a sophisticated wrapper for varying implementations.

Although it is not an overwhelming simple pattern, it is very simple in its use.

The client only has to instantiate the abstraction, stuff it with the desired implementation and it is ready for use. Which implementation you choose doesn’t matter, you always call the same method (Operation).

class Client
{
    static void Main()
    {
        Abstraction abstraction = new RefinedAbstraction();
        // Set implementation and call
        abstraction.Implementor = new ConcreteImplementor1();
        abstraction.Operation();

        // Change implemention and call
        abstraction.Implementor = new ConcreteImplementor2();
        abstraction.Operation();

        Console.ReadKey();
    }
}

The abstract class Implementor defines the method (OperationImp) that must be implemented by the concrete classes.

abstract class Implementor
{
    public abstract void OperationImp();
}

The abstraction class contains a implementor and a virtual method Operation, that calls the concrete method of the implementor.

class Abstraction
{
    protected Implementor implementor;
    public Implementor Implementor
    {
        set
        {
            implementor = value;

        }
    }
    public virtual void Operation()
    {
        implementor.OperationImp();
    }
}

The refined abstraction derives from abstraction and overrides the operation. This comes in handy later on when you want to refine the abstraction. When that moment comes, you don’t have to break the original abstraction.

class RefinedAbstraction : Abstraction
{
    public override void Operation()
    {
        implementor.OperationImp();
    }
}

The concrete classes implement the method OperationImp.

// First implementation
class ConcreteImplementor1 : Implementor
{
    public override void OperationImp()
    {
        Console.WriteLine("ConcreteImplementor1.OperationImp");
    }
}

// Second implementation
class ConcreteImplementor2 : Implementor
{
    public override void OperationImp()
    {
        Console.WriteLine("ConcreteImplementor2.OperationImp");
    }
}

You can click here for a simplified

class Client
{
    static void Main()
    {
        Message message = new WelcomeMessage();

#if DEBUG
        // Change implemention to Test implementation
        message.Transporter = new TestTransporter();
        message.Send();
#else
        // Real implementation
        message.Transporter = new EmailTransporter();
        message.Send();
#endif
        Console.ReadKey();
    }
}

abstract class TransporterBase
{
    public abstract void Send();
}

class Message
{
    protected TransporterBase transporter;
    public TransporterBase Transporter
    {
        set { transporter = value; }
    }

    public virtual void Send()
    {
        transporter.Send();
    }
}

class WelcomeMessage : Message
{
    public override void Send()
    {
        transporter.Send();
    }
}

class EmailTransporter : TransporterBase
{
    public override void Send()
    {
        //Email logic
    }
}

class TestTransporter : TransporterBase
{
    public override void Send()
    {
        // Please, do not spam us with testmessages.
    }
}

This post is part of my series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern and look at simplified real-world C# code that implements the pattern.

The Singleton pattern is used to restrict the instantiation of a class to just one object. The singleton pattern must satisfy the single instance and global access principles.

image

A nice pattern, but: Why not use a global static variable?

The answer lies in the fact that this generally is not considered object-oriented. However, there are various different ways to implement the Singleton pattern, one more elegant than the other.

In the original implementation the client just creates a singleton and does its work, like setting and getting a ‘global’ variable.

class Client
{
    static void Main(string[] args)
    {
        // Create one singleton
        Singleton singleton1 = Singleton.CreateInstance();
        // and store a value
        singleton1.Value = "Hello, world";

        // Create 'another' singleton
        Singleton singleton2 = Singleton.CreateInstance();
        // and read the value.
        Console.WriteLine(singleton2.Value);

        Console.ReadKey();
    }
}

Instantiation of a singleton is done by calling its instantiation method. It checks if it is already instantiated. If this is the case, it returns the object. Otherwise, it creates one.

public sealed class Singleton
{
    public string Value = "Unknown";
    static Singleton instance = null;

    Singleton()     {  }

    public static Singleton CreateInstance()
    {
        if (instance == null)
        {
            instance = new Singleton();
        }
        return instance;
    }
}

The problem with this code is that it is not thread-safe. As a result, it is possible to create more instance. This is an unwanted side-effect of multithreading. You could use locking, but there is also a lock-free and thread-safe version.

public sealed class Singleton
{
    public string Value = "Unknown";
    static readonly Singleton instance = new Singleton();

    // explicit static constructor
    static Singleton()  {  }

    Singleton()   {  }

    public static Singleton CreateInstance()
    {
        return instance;
    }
}

I certainly like this one! Read more about the pros and cons in the article Implementing the Singleton Pattern in C#, written by John Skeet.

Want to see a simplified real world example? Just rename Singleton to Logger and implement a method Log, like this:

class Client
{
    static void Main(string[] args)
    {
        Logger logger = Logger.CreateLogger();

        // log an important message
        logger.Log("Hello, world");

        Console.ReadKey();
    }
}

public sealed class Logger
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    static readonly Logger logger = new Logger();

    static Logger()  {  }

    Logger()  {  }

    public static Logger CreateLogger()
    {
        return logger;
    }
}

See? The Singleton is a powerful pattern if you implement it correctly.

This post is part of my series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern and look at simplified real-world C# code that implements the pattern.

The Memento pattern provides you with the ability to restore an object to its previous state (undo by rollback).

image

The Memento pattern can have different purposes, but above all is known as the Undo Pattern. If you are mentally in an object oriented mood you could ask yourself…

Why on earth and above want they to put the internal data outside of the class in question? That’s not data hiding, is it?

… but the truth is that memento pattern doesn’t violate encapsulation of the internal state.

As a consequence, this pattern can come very handy when you want to store its internal state and reclaim it later without knowledge of the original object.

The client creates an originator object, which has a certain internal state. This can be any object, of course. The important objects are the caretaker and memento. A memento is created by the originator and stored in the caretaker. At a later point in time the previous state can be restored by setting the originators memento to the caretaker’s stored memento.

class Client
{
    public static void Run()
    {
        Originator originator = new Originator();
        originator.State = "First state";
        // a memento is created and stored
        Caretaker caretaker = new Caretaker();
        caretaker.Memento = originator.CreateMemento();
        // change the internal state of the originator object
        originator.State = "Second state";
        Console.WriteLine("Restoring previous state.");
        originator.SetMemento(caretaker.Memento);

    }
}

The originator object can be any object, as long as they implement a CreateMemento and SetMemento method. The CreateMemento method should return a filled memento object, whilst the SetMemento should read the data stored in the memento and restore its internal state.

class Originator
{
    private string m_State;
    public string State
    {
        get { return m_State; }
        set
        {
            m_State = value;
            Console.WriteLine("current state = {0}", m_State);
        }
    }

    public Memento CreateMemento()
    {
        return (new Memento(State));
    }

    public void SetMemento(Memento memento)
    {
        State = memento.State;
    }
}

The Memento object contains the originators internal state, so must have a similar structure. To design a Memento class you could start with a copy of the originator class and strip all unnecessary methods and attributes.

class Memento
{
    private string m_State;
    public Memento(string state)
    {
        this.m_State = state;
    }

    public string State
    {
        get { return m_State; }
    }
}

The Caretaker only contains the memento. In this example there is just one memento, but normally the caretaker contains a list of mementos.

class Caretaker
{
    public Memento Memento;

}

And of course, you can click here for a simplified

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

enum ArticleStatus
{
    Draft,
    PendingReview,
    Published
}

class Client
{
    static void Run(string[] args)
    {
        // initial state
        Article article = new Article();
        article.Status = ArticleStatus.Draft;

        // save state
        StatusStore store = new StatusStore();
        store.StoredStatus = article.CreateStoredStatus();

        // user pressed the publish button
        article.Status = ArticleStatus.Published;
        article.Save();

        // user presse the undo button
        article.RestoreToPreviousState(store.StoredStatus);
        article.Save();
    }
}

class Article
{
    private ArticleStatus m_State;
    public ArticleStatus Status
    {
        get { return m_State; }
        set
        {
            m_State = value;
        }
    }
    public void Save()
    {
        // persisting logic
    }
    public ArticleState CreateStoredStatus()
    {
        return (new ArticleState(Status));
    }

    public void RestoreToPreviousState(ArticleState memento)
    {
        Status = memento.State;
    }
}

class ArticleState
{
    private ArticleStatus m_State;
    public ArticleState(ArticleStatus state)
    {
        this.m_State = state;
    }

    public ArticleStatus State
    {
        get { return m_State; }
    }
}

class StatusStore
{
    public ArticleState StoredStatus;
}

This post is part of my series on the foundational design patterns in C#. In this series I explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Facade pattern is intended to provide an unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystems easier to use.

image In simple terms: this pattern is very useful when you have an great amount of scattered functionality available across a couple of class libraries and you want to provide an unified global point of access for your clients.

The only thing the client has to do is to create the facade class and call its method.

class Client
{
    public static void Main()
    {
        Facade facade = new Facade();
        facade.MethodA();

        Console.ReadKey();
    }
}


The facade class contains all subsystem classes with the necessary methods and provides a method which calls all necessary methods from the belonging subsystem classes.

class Facade
{
    private FirstSubSystem m_FirstSubSystem = new FirstSubSystem();
    private SecondSubSystem m_SecondSubSystem = new SecondSubSystem();

    public void MethodA()
      {
        Console.WriteLine("Facade->MethodA()");
       m_FirstSubSystem.MethodA();
        m_SecondSubSystem.MethodB();
     }
}

The subsystem classes can be anything. For the sake of simplicity in this example they provide only the desirer method.

class FirstSubSystem
{
    public void MethodA()
    {
        Console.WriteLine("* calling FirstSubSystem.MethodA");
    }
}

class SecondSubSystem
{
    public void MethodB()
    {
        Console.WriteLine("* calling SecondSubSystem.MethodB");
    }
}

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

Pages: Prev 1 2 3 4 5 6 7 Next