traits, interface, inheritance

http://stackoverflow.com/questions/9205083/traits-vs-interfaces

Prefer interface to inheritance
use trait for inheritance
If have to use inheritance, use abstract class

is_a => interface

has properties => composition (traits, mixins)

template pattern => abstract class implements interface

inheritance is outdated, should be avoided these days

Advertisements

observer pattern

A very good article:

http://www.dofactory.com/Patterns/PatternObserver.aspx#_self2

Hide code

// Observer pattern — Structural example

using System;

using System.Collections.Generic;

 

namespace DoFactory.GangOfFour.Observer.Structural

{

/// <summary>

/// MainApp startup class for Structural

/// Observer Design Pattern.

/// </summary>

class MainApp

{

/// <summary>

/// Entry point into console application.

/// </summary>

static void Main()

{

// Configure Observer pattern

ConcreteSubject s = new ConcreteSubject();

 

s.Attach(new ConcreteObserver(s, “X”));

s.Attach(new ConcreteObserver(s, “Y”));

s.Attach(new ConcreteObserver(s, “Z”));

 

// Change subject and notify observers

s.SubjectState = “ABC”;

s.Notify();

 

// Wait for user

Console.ReadKey();

}

}

 

/// <summary>

/// The ‘Subject’ abstract class

/// </summary>

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 (Observer o in _observers)

{

o.Update();

}

}

}

 

/// <summary>

/// The ‘ConcreteSubject’ class

/// </summary>

class ConcreteSubject : Subject

{

private string _subjectState;

 

// Gets or sets subject state

public string SubjectState

{

get { return _subjectState; }

set { _subjectState = value; }

}

}

 

/// <summary>

/// The ‘Observer’ abstract class

/// </summary>

abstract class Observer

{

public abstract void Update();

}

 

/// <summary>

/// The ‘ConcreteObserver’ class

/// </summary>

class ConcreteObserver : Observer

{

private string _name;

private string _observerState;

private ConcreteSubject _subject;

 

// Constructor

public ConcreteObserver(

ConcreteSubject subject, string name)

{

this._subject = subject;

this._name = name;

}

 

public override void Update()

{

_observerState = _subject.SubjectState;

Console.WriteLine(“Observer {0}’s new state is {1}”,

_name, _observerState);

}

 

// Gets or sets subject

public ConcreteSubject Subject

{

get { return _subject; }

set { _subject = value; }

}

}

}

singleton pattern

http://en.wikipedia.org/wiki/Singleton_pattern

Example

The Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading. Since Java 5.0, the easiest way to create a Singleton is the enum type approach, given at the end of this section.

Lazy initialization

This method uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs. The problem is that an out-of-order write may allow the instance reference to be returned before the Singleton constructor is executed.[9]

public class SingletonDemo {
        private static volatile SingletonDemo instance = null;

        private SingletonDemo() {       }

        public static SingletonDemo getInstance() {
                if (instance == null) {
                        synchronized (SingletonDemo .class){
                                if (instance == null) {
                                        instance = new SingletonDemo ();
                                }
                      }
                }
                return instance;
        }
}

Eager initialization

If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance:

public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

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

This method has a number of advantages:

  • The instance is not constructed until the class is used.
  • There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

Why the lazy double-check work?

http://www.ibm.com/developerworks/java/library/j-dcl/index.html

Listing 4. Double-checked locking example

                
public static Singleton getInstance()
{
  if (instance == null)
  {
    synchronized(Singleton.class) {  //1
      if (instance == null)          //2
        instance = new Singleton();  //3
    }
  }
  return instance;
}

The theory behind double-checked locking is that the second check at //2 makes it impossible for two different Singleton objects to be created as occurred in Listing 3. Consider the following sequence of events:

  1. Thread 1 enters the getInstance() method.
  2. Thread 1 enters the synchronized block at //1 because instance is null.
  3. Thread 1 is preempted by thread 2.
  4. Thread 2 enters the getInstance() method.
  5. Thread 2 attempts to acquire the lock at //1 because instance is still null. However, because thread 1 holds the lock, thread 2 blocks at //1.
  6. Thread 2 is preempted by thread 1.
  7. Thread 1 executes and because instance is still null at //2, creates a Singleton object and assigns its reference to instance.
  8. Thread 1 exits the synchronized block and returns instance from the getInstance() method.
  9. Thread 1 is preempted by thread 2.
  10. Thread 2 acquires the lock at //1 and checks to see if instance is null.
  11. Because instance is non-null, a second Singleton object is not created and the one created by thread 1 is returned.

Note: think about if there is no line #2, there will be the case each thread return a different instance

related links: http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104

http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function

Find What Is Varying and Encapsulate It

http://www.informit.com/articles/article.aspx?p=167890&seqNum=4

Containing variation in data versus containing variation in behavior

Suppose I am working on a project that models different characteristics of animals. My requirements are the following:

Each type of animal can have a different number of legs.

Animal objects must be able to remember and retrieve this information.

Each type of animal can have a different type of movement.

Animal objects must be able to return how long it will take to move from one place to another given a specified type of terrain.

A typical approach of handling the variation in the number of legs would be to have a data member containing this value and having methods to set and get it. However, one typically takes a different approach to handling variation in behavior.

Suppose there are two different methods for moving: walking and flying. These requirements need two different pieces of code: one to handle walking and one to handle flying; a simple variable won’t work. Given that I have two different methods, I seem to be faced with a choice of approach:

Having a data member that tells me what type of movement my object has.

Having two different types of Animals (both derived from the base Animal class)—one for walking and one for flying.

Unfortunately, both of these approaches have problems:

Tight coupling—The first approach (using a flag with presumably a switch based on it) may lead to tight coupling if the flag starts implying other differences. In any event, the code will likely be rather messy.

Too many details—The second approach requires that I also manage the subtype of Animal. And I cannot handle Animals that can both walk and fly.

Handling variation in behavior with objects

A third possibility exists: have the Animal class contain an object that has the appropriate movement behavior.

delagation pattern

http://en.wikipedia.org/wiki/Delegation_pattern

Advantage: easy to compose behavior, and easy to change what to be composed.

Disadvantage: harder to understand and inefficient

In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a delegate, is given the responsibility to execute a task for the delegator.

In this Java example, the Printer class has a print method. This print method, rather than performing the print itself, delegates to class RealPrinter. To the outside world it appears that the Printer class is doing the print, but the RealPrinter class is the one actually doing the work.

Delegation is simply passing a duty off to someone/something else. Here is a simple example:

 class RealPrinter { // the "delegate"
     void print() { 
       System.out.println("something"); 
     }
 }

 class Printer { // the "delegator"
     RealPrinter p = new RealPrinter(); // create the delegate 
     void print() { 
       p.print(); // delegation
     } 
 }

 public class Main {
     // to the outside world it looks like Printer actually prints.
     public static void main(String[] args) {
         Printer printer = new Printer();
         printer.print();
     }
 }

why interfaces (pure virtual functions) exist?

http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface

their use as a language construct by thinking of them as means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.

For example — say you have a SIM game and have the following classes:

class HouseFly inherits Insect {
void FlyAroundYourHead();
void LandOnThings();
}

class Telemarketer inherits Person {
void CallDuringDinner();
void ContinueTalkingWhenYouSayNo();
}

Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying.

Let’s say our game needs to have some sort of random thing that annoys the game player when they eat dinner. This could be a HouseFly or a Telemarketer or both — but how do you allow for both with a single function? And how do you ask each different type of object to “do their annoying thing” in the same way?

The key to realize is that both a Telemarketer and HouseFly share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let’s make an interface that both can implement:

interface IPest {
void BeAnnoying();
}

class HouseFly inherits Insect implements IPest {
void FlyAroundYourHead();
void LandOnThings();

void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}

class Telemarketer inherits Person implements IPest {
void CallDuringDinner();
void ContinueTalkingWhenYouSayNo();

void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}

We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics — they simply need to satisfy the contract of IPest — that contract is simple. You just have to BeAnnoying. In this regard, we can model the following:

class DiningRoom {

DiningRoom(Person[] diningPeople, IPest[] pests) { … }

void ServeDinner() {
when diningPeople are eating,

foreach pest in pests
pest.BeAnnoying();
}
}

Here we have a dining room that accepts a number of diners and a number of pests — note the use of the interface. This means that in our little world, a memeber of the pests array could actually be a Telemarketer object or a HouseFly object.

The ServeDinner method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that’s when our pests do their work — each pest is instructed to be annoying by way of the IPest interface. In this way, we can easily have both Telemarketers and HouseFlys be annoying in each of their own ways — we care only that we have something in the DiningRoom object that is a pest, we don’t really care what it is and they could have nothing in common with other.