Archive

Archive for the ‘C#’ Category

Simple Callback

January 7, 2015 Leave a comment

Callback is a function that is executed when some other function is done with its work.

Example Code:

using UnityEngine;
using System.Collections;

public class SimpleCallback : MonoBehaviour 
{
    delegate void delegateCaller();

    void DoACall()
    {
        Debug.Log("Do A Call");
    }

    void DoAnotherCall()
    {
        Debug.Log("Do Another Call");
    }

    IEnumerator StartATask(delegateCaller callThis)
    {
        Debug.Log("Starting...");
        yield return new WaitForSeconds(1);
        Debug.Log("Done.");
        callThis();
    }

    // Use this for initialization
    void Start () 
    {
        StartCoroutine(StartATask(DoACall));
        StartCoroutine(StartATask(DoAnotherCall));
    }
    

}

Output

Starting...
Starting...
Done.
Do A Call
Done.
Do Another Call
Categories: C#, Programming, Unity

Adapter

June 22, 2014 Leave a comment

Frequency of Use Medium – High Intent Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. Structure Adapter Applicability Use the Adapter pattern when:

  • you want to use an existing class, and its interface does not match the one you need.
  • you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don’t necessarily have compatible interfaces.
  • (object adapter only) you need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class

Implementation Code (C#)

using System;
public class MainClass {
 public static void Main() {
  Target target = new Adapter();
  target.Request();
 }
}

 class Target {
  public virtual void Request() {
   Console.WriteLine("Called Target Request");
  }
 }
 
 class Adapter : Target {
 private Adaptee _adaptee = new Adaptee();
 
 public override void Request() {
  _adaptee.SpecificRequest();
  }
 }
 
 class Adaptee {
  public void SpecificRequest() {
   Console.WriteLine("Called Adaptee specific Request");
  }
 }

Code Output

 Called Adaptee specific Request
Categories: C#, Design Pattern, Programming

Observer

June 8, 2014 Leave a comment

Frequency of Use
High

Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Structure

20140608-185029-67829449.jpg

Applicability
Use the Observer pattern in any of the following situations:

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  • When a change to one object requires changing others, and you don’t know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.

 

Code Implementation (C#)

using System;
using System.Collections.Generic;

namespace Observer
{
 public class MainClass
 {
  public static void Main()
  {
    ConcreteSubject s = new ConcreteSubject();
    s.Attach(new ConcreteObserver(s, "X"));
    s.Attach(new ConcreteObserver(s, "Y"));
    s.Attach(new ConcreteObserver(s, "Z"));

    s.SubjectState = "ABCD";
    s.Notify();

    Console.ReadKey();
  }
 }

 abstract class Subject
 {
  private List<Observer> _observers = new List<Observer>();

  public void Attach(Observer observer)
  {
    _observers.Add(observer);
  }

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

  public void Notify()
  {
   foreach (var observer in _observers)
   {
    observer.Update();
   }
  }
 }

 class ConcreteSubject : Subject
 {
  private string _subjectState;

  public string SubjectState
  {
    get { return _subjectState; }
    set { _subjectState = value; }
  }
 }

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

 class ConcreteObserver : Observer
 {
   private string _name;
   private ConcreteSubject _subject;
   private string _observerState;

   public ConcreteObserver(ConcreteSubject subject, string name)
   {
     this._subject = subject;
     this._name = name;
   }

   public override void Update()
   {
    _observerState = _subject.SubjectState;
    Console.WriteLine("State of Observer {0} is {1}",
                      _name, _observerState);

   }

   public ConcreteSubject Subject
   {
    get { return _subject; }
    set { _subject = value; }
   }

  }
 }

Code Output

State of Observer X is ABCD 
State of Observer Y is ABCD 
State of Observer Z is ABCD
Categories: C#, Design Pattern, Programming

Flyweight

May 31, 2014 Leave a comment

Frequency of Use
Low

Intent
Use sharing to support large numbers of fine-grained objects efficiently.

Structure

20140531-125430-46470258.jpg

Applicability
The Flyweight pattern’s effectiveness depends heavily on how and where it’s used. Apply the Flyweight pattern when all of the following are true:

  • An application uses a large number of objects.
  • Storage costs are high because of the sheer quantity of objects.
  • Most object state can be made extrinsic.
  • Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.
  • The application doesn’t depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

Code Implementatio  (C#)

using System;
using System.Collections;

namespace Flyweight
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            FlyweightFactory ff = new FlyweightFactory();

            int state = 20;
            Flyweight fx = ff.GetFlyweight("X");
            fx.Operation(state);

            Flyweight fy = ff.GetFlyweight("Y");
            fy.Operation(state);

            Flyweight fz = ff.GetFlyweight("Z");
            fz.Operation(state);

            UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();
            fu.Operation(state);

        }
    }

    class FlyweightFactory
    {
        private Hashtable _flyweights = new Hashtable();

        public FlyweightFactory()
        {
            _flyweights.Add("X", new ConcreteFlyweight());
            _flyweights.Add("Y", new ConcreteFlyweight());
            _flyweights.Add("Z", new ConcreteFlyweight());

        }

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

    abstract class Flyweight
    {
        public abstract void Operation(int extrinsicstate);
    }

    class ConcreteFlyweight : Flyweight
    {
        public override void Operation(int extrinsicstate)
        {
            Console.WriteLine("ConcreteFlyweight:" + extrinsicstate);
        }
    }

    class UnsharedConcreteFlyweight : Flyweight
    {
        public override void Operation(int extrinsicstate)
        {
            Console.WriteLine("UnsharedConcreteFlyweight:" + extrinsicstate);
        }
    }

}

Code Output

ConcreteFlyweight:20
ConcreteFlyweight:20
ConcreteFlyweight:20
 
UnsharedConcreteFlyweight:20
Categories: C#, Design Pattern, Programming

Command

May 26, 2014 Leave a comment

Frequency of Use
medium to high

Intent
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Structure
Command

Applicability

  • Express parameterization in a procedural language with a callback function, that is, a function that’s registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks.
  • specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address space-independent way, then you can transfer a command object for the request to a different process and fulfill the request there.
  • support undo. The Command’s Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.
  • support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.
  • structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.

Code Implementation (C#)

using System;

namespace Command
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Receiver receiver = new Receiver();
            Command command = new ConcreteCommand(receiver);
            Invoker invoker = new Invoker();

            invoker.SetCommand(command);
            invoker.ExecuteCommand();
        }
    }

    class Receiver
    {
        public void Action()
        {
            Console.WriteLine("Called Receiver.Action();");
        }
    }

    abstract class Command
    {
        protected Receiver _receiver;

        public Command(Receiver receiver)
        {
            this._receiver = receiver;
        }

        public abstract void Execute();
    }

    class ConcreteCommand : Command
    {
        public ConcreteCommand(Receiver receiver) : base(receiver)
        {

        }

        public override void Execute ()
        {
            _receiver.Action();
        }
    }

    class Invoker
    {
        private Command _command;

        public void SetCommand(Command command)
        {
            this._command = command;
        }

        public void ExecuteCommand()
        {
            _command.Execute();
        }
    }
}

Code Output

Called Receiver.Action();

 

Categories: C#, Design Pattern, Programming

State

May 11, 2014 Leave a comment

Frequency of Use
Medium

Intent
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Structure
State

Applicability
Use the State pattern in either of the following cases:

  • An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state.
  • Operations have large, multipart conditional statements that depend on the object’s state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object’s state as an object in its own right that can vary independently from other objects.

Code Implementation

using System;

namespace State
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Context c = new Context(new ConcreteStateA());
            c.Request();
            c.Request();
            c.Request();
            c.Request();
        }
    }

    abstract class State
    {
        public abstract void Handle(Context context);
    }

    class ConcreteStateA : State
    {
        public override void Handle(Context context)
        {
            context.State = new ConcreteStateB();
        }
    }

    class ConcreteStateB : State
    {
        public override void Handle(Context context)
        {
            context.State = new ConcreteStateA();
        }
    }


    class Context
    {
        private State _state;

        public Context(State state)
        {
            this.State = state;
        }

        public State State
        {
            get {return _state;}
            set 
            {
                _state = value
                Console.WriteLine("State: " + _state.GetType().Name);

            }
        }

        public void Request()
        {
            _state.Handle(this);
        }

    }
}

Code Output

State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
Categories: C#, Design Pattern, Programming

Prototype

May 11, 2014 Leave a comment

Frequency of Use
Medium

Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Structure
Prototype

Applicability
Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; and

  • when the classes to instantiate are specified at run-time, for example, by dynamic loading; or
  • to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or
  • when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Code Implementations (C#)

using System;

namespace Prototype
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            ConcretePrototype1 p1 = new ConcretePrototype1("I");
            ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
            Console.WriteLine("Clone {0}",c1.Id);

            ConcretePrototype2 p2 = new ConcretePrototype2("II");
            ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
            Console.WriteLine("Clone {0}",c2.Id);

            Console.ReadKey();
        }
    }

    abstract class Prototype
    {
        private string _id;

        public Prototype(string id)
        {
            this._id = id;
        }

        public string Id 
        {
            get { return _id; }
        }

        public abstract Prototype Clone();
    }

    class ConcretePrototype1 : Prototype
    {
        public ConcretePrototype1(string id) : base(id)
        {
        }

        public override  Prototype Clone()
        {
            return (Prototype)this.MemberwiseClone() ;
        }

    }

    class ConcretePrototype2 : Prototype
    {
        public ConcretePrototype2(string id) : base(id)
        {

        }

        public override Prototype Clone()
        {
            return (Prototype)this.MemberwiseClone();
        }
    }
}

Code Output

Clone I
Clone II
Categories: C#, Design Pattern, Programming