Posts

Showing posts from 2012

Decorator Pattern

This is an example of the Decorator pattern, in this case a decorator for ObservableCollection.  Working with WPF and ObservableCollection using threads, one will run into the problem whereby the ObservableCollection cannot be updated from outside the owning thread; Delegates and Invoke will not work. A solution is to contain and expand the class, as is done in this example on michIG's Blog.

This linked file contains the original code in C#, as well as the same code converted to VB.NET.

Salient Characteristic(s)
Sets an internal pointer to the decorated object, sending method calls and property actions to the internal objectExtends the object by wrapping it and adding some aspect handled by the decorator
Code

using System;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Collections.Specialized;
using System.ComponentModel;

namespace DesignPatterns
{
    /// <summary>  
    /// This class is an observablecollection which invokes automatically.  
    /// T…

Composite Pattern

A implementation of the composite pattern similar to a class that would be used for constructing a binary search tree.  Better, more detailed implementations are known as red-black or AVL trees.

Salient Characteristic(s)
Reduces complexity by treating objects consistently, as opposed to having different methods and properties for each collectionAny modification method of a collection would nbe the same as modifying the containerCode

namespace DesignPatterns
{
    /// <summary>
    /// An example of composite that might be used in a binary tree
    /// In this case, the tree node is composed of tree nodes
    /// Any modification method of a node, would be the same as modifying the node itself
    /// </summary>
    public class TreeNode 
    {
        private int _Value;
        public int Value
        {
            get { return _Value; }
            set { _Value = value; }
        }

        private TreeNode _Parent;
        public TreeNode Parent
        {
            get { return _Parent; }

Bridge Pattern

A bare-bones, generic implementation of the bridge pattern, using inheritance, polymorphism, and abstraction. 

Salient Characteristic(s)

Decouple classes, allowing them to vary independentlyUseful when frequent changes are made to classes
Code

namespace DesignPatterns

{
    /// <summary>
    /// The implementor: the abstract class, and concrete implementation of one side of the relation
    /// </summary> 
    public interface IBridgeAbstraction
    {
        void Build();
    }

    abstract class BridgeAbstraction : IBridgeAbstraction
    {
        public abstract void Build();
    }

    class ConcreteBridge1 : BridgeAbstraction
    {
        public override void Build()
        {
        }
    }

    class ConcreteBridge2 : BridgeAbstraction
    {
        public override void Build()
        {
        }
    }


    /// <summary>
    /// The abstract class, and concrete implementation of other side of the relations 
    /// </summary>
    public abstract class AbstractionBridgeSupplier
    { 
   …

Abstract Cat Factory (Amusement)

Image
A friend amusingly posted on Facebook a retro photograph of four (4) 'designers' around a cat, with the caption alluding to designing hats for cats, and so I decided to make, somewhat incongruously, an abstract cat factory, which varies by the location of the cat..  

Salient Characteristic(s)
Classes derived from abstract typesClass creates derived (concrete) classes based on type requiredCode

namespace DesignPatterns
{
    public enum Location
    {
        Kitchen,
        Bedroom,
        LivingRoom
    }

    public enum Amusements
    {
        String,
        Mouse,
        Food,
        Sleep
    }

    public abstract class Feline
    {
        public abstract Feline HereKittyKitty();
    }

    public class Cat : Feline
    {
        private Location _Location;
        private Feline _Cat = null;
        private Amusements _Amusement;
        public Cat(Location location)
        {
            _Location = location;
        }

        public override Feline HereKittyKitty()
        {
            switch (_…

Adapter or Wrapper

This is code possible through .NET, in that it bridges across to COM for automation in VBA.  This concept can be extended to work for many other COM-based applications.  This code allows the add-in to expose internal .NET-coded procedures to Excel COM, extending the use of the .NET code.

Salient Characteristic(s)

Handle interface between different, incompatible systemsThe interface is required because COM is interface-basedOther code elements are required for this to work properlyRegistering the DLLCreating the AdapterForVBA class on startupCode

using System;
using System.Runtime.InteropServices;

namespace DesignPatterns
{
    /// <summary>
    /// Interace to expose VSTO/COM obects for COM and Excel
    /// Used by class below
    /// </summary>
    [ComVisible(true)]
    [Guid("B523844E-1A41-4118-A0F0-FDFA7BCD77C9")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IAdapterForVba
    {
        //signatures for methods acessible to VBA go here
        /…

Facade

This is derived from actual code of mine, and elements of this sample combine the Facade pattern with the Publisher (Observer) pattern.  The primary class, based on the ISubscriber interface, is fairly complicated to use, requiring delegates, threading, and asynchronous callbacks.  The facade, based on ISubscriberFacade, encapsulates all the methods required to work with the Windows Communication Foundation (WCF) service , handling threading, delegate creation, and asynchronous callbacks internally, so that that the clients only need to create the object.  I wrote the encapsulating client to ease the adoption of the WCF service for legacy clients, seeing that the code complexity was likely a hurdle.

Salient Characteristic(s)

Reduces or hides complexities to other clients or systemsSimplified interaction between systems and/or typesNote

DispatchingObservableCollection is based on ObservableCollection commonly used in Windows Presentation Foundation (WPF) applications and available from on…

Multiton

A fairly simple example of the multiton pattern, with a private constructor, and a tracker for created objects, the name being an integer identifier.

Salient Chacteristic(s)
A private keyed list for tracking objectsA private constructorNamed objectsCode

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

namespace DesignPatterns
{
    public class Multiton
    {
        //read-only dictionary to track multitons
        private static IDictionary<int, Multiton> _Tracker = new Dictionary<int, Multiton> { };

        private Multiton()
        {
        }

        public static Multiton GetInstance(int key)
        {
            //value to return
            Multiton item = null;

            //lock collection to prevent changes during operation
            lock (_Tracker)
            { 
                //if value not found, create and add
                if(!_Tracker.TryGetValue(key, out item))
                {
                    item = new Multiton();

                    //calculate next key
       …

Singleton

The Singleton design pattern seems generally frowned upon, except for use in logging classes.  Below are several variants of the Singleton design pattern, of which, only the thread-safe version merits attention:


Salient Chacteristic(s)

A private constructorStatic variable for self-trackingThree (3) variants
EagerLazyThread-safe (Double-checked Locking)
Code


namespace DesignPatterns
{

    //double-checked locking singleton
    //required for threaded environments
    public class DoubleCheckingSingleton
    {
        private static volatile DoubleCheckingSingleton _Instance = null;
        private static object _SyncRoot = new object();

        //Private constructor prevents instantiation from other classes
        private DoubleCheckingSingleton()
        {
            //class contruction
        }

        public static DoubleCheckingSingleton Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (_SyncRoot)
                    {
    …

Prototype

Whereas ICloneable will be used to return a shallow copy, the data object's attribute Serializable enables creation of a deep copy of the data object, instead of a reference:

Salient Chacteristic(s)
Shallow copies use the native IConeable InterfaceDeep copies requires use of creation of new objects, not referencesFor this, use of Serializable attribute to create a new copiesCode

using System;
using System.IO;
using Serialization = System.Runtime.Serialization;

namespace DesignPatterns
{
    /// <summary>
    /// A serializable data object, the attribute
    ///  necessary for simple form of deep copy
    /// </summary>
    [Serializable]
    public class SerializableDataObject 
    {
        public SerializableDataObject(int objectId)
        {
        }

        private int _Id;
        public int Id
        {
            get
            {
                return _Id;
            }
            set
            {
                _Id = value;
            }
        }
    }

    public static class CommonM…

Lazy Initialization

A fairly straightforward 'fill-in-the-blanks' example of a Lazy Initialization design pattern, except that this uses an enumeration for the type - I hate passing strings, so easy to screw up - as well as a struct for the type that is lazily initialized:

Code

using System;
using System.Collections.Generic;

namespace DesignPatterns
{
    public class LazyFactoryObject
    {
        //internal collection of items
        //IDictionaery makes sure they are unique
        private IDictionary<LazyObjectType, LazyObject> _LazyObjectList = 
            new Dictionary<LazyObjectType, LazyObject>();

        //enum for passing name of type required
        //avoids passing strings and is part of type ahead
        public enum LazyObjectType
        { 
            None,
            Small,
            Big,
            Bigger,
            Huge
        }

        //standard type of object that will be constructed
        public struct LazyObject
        {
            public LazyObjectType Name;
           …