Saturday, July 17, 2010

Singleton pattern with with C# code example

Definition
The singleton patterns ensures a class has only one instance, and provide a global point of access it.

More information
To assure there is one and only one instance, first we can disable the object creation by making constructor private. Then secondly we can mark instance variable/method to static to ensure only one instance and to provide access point.

The Instance() method is the method that return the singleton instance. We can mark this method as lock (syncronized) to make thread safe. But lock (syncronized) is not good for performance. So what are the other available options,
  • No worry about the Instance method if the performance is not important :P
This is obvious, if the performance is not a critical factor then you can use syncronization.
  • Do the instance creation as eagerly created rather than a lazy created one
Static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain.
  • Use double check locking to reduce the use of syncronized Instance method
C# you can easily do this but in Java you need to do this with Volatile keyword. Also you need Java 1.5 or higher version. Please see the reference for more details.


Implementation

This implementation is a non lazy implementation of the singleton pattern. This is a thread safe version.

internal class Singleton
{
private static Singleton _instance = new Singleton();

private string _property = "Singleton Property";

private Singleton()
{
}

public string Property
{
get { return _property; }
set { _property = value; }
}

public static Singleton Instance
{
get { return _instance; }
set { _instance = value; }
}
}

This implementation is a lazy implementation of the singleton pattern. This is not a thread safe version.



internal class SingletonLazy
{
private static SingletonLazy _instance;
private string _property = "Singleton Property";

private SingletonLazy()
{
}

public string Property
{
get { return _property; }
set { _property = value; }
}

public static SingletonLazy Instance()
{
if (_instance == null)
{
_instance = new SingletonLazy();
}
return _instance;
}
}

This is the Main program to work with above classes.


internal class Program
{
private static void Main(string[] args)
{
// The non lazy initialization
Singleton nonLazySingleton1 = Singleton.Instance;
Singleton nonLazySingleton2 = Singleton.Instance;
nonLazySingleton1.Property = "The new Property";

if (nonLazySingleton1.Property.Equals(nonLazySingleton2.Property))
{
Console.WriteLine("The non lazy singleton is successful");
}

// The lazy initialization
SingletonLazy singletonLazy1 = SingletonLazy.Instance();
SingletonLazy singletonLazy2 = SingletonLazy.Instance();
singletonLazy2.Property = "The new Property";

if (singletonLazy1.Property.Equals(singletonLazy2.Property))
{
Console.WriteLine("The lazy singleton is successful");
}
}
}


Reference:
http://www.yoda.arachsys.com/csharp/singleton.html

Factory Method with C# code example

Definition
The factory method pattern defines an interface for creating an object, but let subclasses decides which class to instantiate.



The Class digram



The implementation

  • Vehicle Factory :- Abstract Factory


public abstract class VehicleFactory
{
public enum VehicleType
{
Car,
Bicycle
}

public abstract Vehicle CreateVehicle(VehicleType vehicleType);

public Vehicle OrderVehicle(VehicleType vehicleType)
{
Console.WriteLine("You are Ordering a " + vehicleType);
return CreateVehicle(vehicleType);
}
}


  • Bicycle, Car Factory :- Concrete Factory



  • public class BicycleFactory : VehicleFactory
    {
    public override Vehicle CreateVehicle(VehicleType vehicleType)
    {
    Console.WriteLine("Creating a " + vehicleType);
    return new MotorBicycle();
    }
    }



    public class CarFactory : VehicleFactory
    {
    public override Vehicle CreateVehicle(VehicleType vehicleType)
    {
    Console.WriteLine("Creating a " + vehicleType);
    return new Car();
    }
    }


  • Vehicle :- Abstract Product


  • public abstract class Vehicle
    {

    private int _engineCapacity;
    private int _noOfWheels;

    public int EngineCapacity
    {
    get
    {
    return _engineCapacity;
    }
    set
    {
    _engineCapacity = value;
    }
    }

    public int NoOfWheels
    {
    get
    {
    return _noOfWheels;
    }
    set
    {
    _noOfWheels = value;
    }
    }

    public abstract void Accelerate();

    public abstract void Break();
    }


  • MotorBicycle, Car :- Concrete Product



public class MotorBicycle : Vehicle
{
public MotorBicycle()
{
base.EngineCapacity = 100;
base.NoOfWheels = 2;
}

public override void Accelerate()
{
Console.WriteLine("Accelerating with Handle");
}

public override void Break()
{
Console.WriteLine("Stopping with Handle");
}
}



public class Car : Vehicle
{
public Car()
{
base.EngineCapacity = 300;
base.NoOfWheels = 4;
}

public override void Accelerate()
{
Console.WriteLine("Accelerating with Paddle");
}

public override void Break()
{
Console.WriteLine("Stopping with Paddle");
}
}


  • Prorgam :- Cleint


class Program
{
static void Main(string[] args)
{
Console.WriteLine("Creating a Motor Bicycle");
VehicleFactory bicycleFactory = new BicycleFactory();
Vehicle motorBicycle = bicycleFactory.CreateVehicle(VehicleFactory.VehicleType.Bicycle);
Console.WriteLine("Got a " + motorBicycle.GetType() + " with EngineCapacity " + motorBicycle.EngineCapacity + " and " + motorBicycle.NoOfWheels + " wheels.");
motorBicycle.Accelerate();
motorBicycle.Break();

Console.WriteLine("");
Console.WriteLine("");

Console.WriteLine("Creating a Car");
VehicleFactory carFactory = new CarFactory();
Vehicle car = carFactory.CreateVehicle(VehicleFactory.VehicleType.Car);
Console.WriteLine("Got a " + car.GetType() + " with EngineCapacity " + car.EngineCapacity + " and " + car.NoOfWheels + " wheels.");
car.Accelerate();
car.Break();

Console.ReadLine();
}
}

Thursday, July 15, 2010

The Abstract Factory pattern with C# code example


The Abstract Factory
The The Abstract Factory is a design pattern which provides an interface for creating families of related or dependent objects without specifying their concrete classes.

The class diagram








































The implementation

  • Animal Factory :- Abstract Factory
This abstract factory defines method/s for producing the product (in our case Animal). All other concrete factories should implement this/these methods.



interface AnimalFactory
{
Animal CreateAnimal();
}



  • LandFactory, SeaFactory :- Concrete Factories
These are concrete factories, implements different product families. Client can use one of these to create a product (in our case Animal), so client never need to create product object.


class LandFactory : AnimalFactory
{
public Animal CreateAnimal()
{
return new Horse();
}
}

class SeaFactory : AnimalFactory
{
public Animal CreateAnimal()
{
return new Seahorse();
}
}

  • Animal :- Abstract Product



public interface Animal
{
void Move();
}


  • Horse, SeaHorse :- Concrete Product




class Horse : Animal
{
public void Move() {
Console.WriteLine("I Can run very fastly!");
}
}

class Seahorse : Animal
{
public void Move() {
Console.WriteLine("I am moving in the water! He he!");
}
}


  • AnimalWorld:- Client
This is the client and it was written against the abstract factory and it will deal actual factory and the product in the run time. The Program class is having the main method as the entry point



class AnimalWorld
{
private Animal animal;

public AnimalWorld(AnimalFactory animalFactory)
{
animal = animalFactory.CreateAnimal();
}

public void Move()
{
animal.Move();
Console.ReadLine();
}
}



class Program
{
static void Main(string[] args)
{
AnimalFactory animalFactory = createAnimalFactory("land");
AnimalWorld animalWorld = new AnimalWorld(animalFactory);
animalWorld.Move();
}

public static AnimalFactory createAnimalFactory(String type)
{
if ("sea".Equals(type))
return new SeaFactory();
else if ("land".Equals(type))
return new LandFactory();
else
return null;
}
}



References:
http://www.dofactory.com/Patterns/PatternAbstract.aspx#_self2
http://en.wikipedia.org/wiki/Abstract_factory_pattern

Saturday, January 30, 2010

භාවනාව

භාවනා වැඩීමට පෙර ඔබ තුල තිබිය යුතු සුදුසුකම්
• නිදහස් චින්තනය
• මනස දියුනු කිරීමේ වටිනාකම ගැන තේරුම් කර ගැනීම
• ජීවිතය ගෙවීයාමට කලින් ප්‍රයොජනයක් ගත යුතු බවට මතයකට පැමිණ සිටීම
• සිත දියුනු කිරීමේ සියලු උපදෙස් බුදු දහමේ ඇති බවට පැහැදීම

සමත භාවනාවත් විදර්ශනා භාවනාවත් යනු ජීවිතාවබෝධයට වැදගත් වන භාවනා දෙකකි. සමත භාවනාව ප්‍රගුණ කිරීමෙන් සිතෙහි දියුනුව වර්ධනයවේ (සිතෙහි දුර්වලකම් නැතිවේ, සිත විසෙරෙන ගතිය නැතිවේ, ශක්තිමත් වේ, යමක් අවබෝධකර ගැනීමට සුදුසු අකාරයට සිත සකස් වේ ). විදර්ශනා භාවනාව දියුනු කිරීමෙන් ප්‍රඤ්ඥාව දියුනුවේ (යම් කිසි දෙයක ඇත්ත ස්වභාවය තේරුම් ගැනීමට හැකිවේ). මෙ භාවනා දෙකම එකිනෙකින් වෙන්කිරීම අපහසුය.

සමත භාවනාව
සමත භාවනාව වැඩීමෙන් පංච නීවරන ධරම යටපත් කොට, සිත තැම්පත් කොට, සමාධිය දියුනු කොට සිත දියුනු කිරීමට හැකිවේ.

පංච නීවරන ධර්ම
• කාමචන්ධය
තමන් අසා කරන රූප, ගන්ධ, ශබ්ද, රස හා ස්පර්ශ වලට සිත නිතර නිතර ඇලී යාම.
• ව්‍යාපද නීවරනය
ඉහත සදහන් කල සැප විදීම් මෙනෙහි කරමින් ඒතුල ගැටීම
• තීන මිත්ත
සිත දියුනු කිරීමට බැරි මට්ටමට තමන් අලස වීම
• උද්දච්ච කුක්කුච්ච
තමන්ගෙන් සිදුවුන අත්වැරදි ගැන මෙනෙහි කිරීමෙන් ශොක වෙමින් ධර්ම මර්ගයෙහි නොහැසිරීම
• විචිකිච්චා
තමන්ට ධර්ම මාරගයෙහි හැසිරීමට බැරිය යනුවෙන් ඇති වන්නාවූ සැකය (මෙය පසුබැසීමට හෙතුවේ).

මෙවැනි කරුනු සිතෙන් යටපත් කර සිත සමාදි ගත කිරීමේ හැකියාවක් සමත භාවනවට ඇත. මෙම සමාධි ගත වීම තුලින් පිලිවෙලින් පලමු, දෙවන, තෙවන හා සිවුවෙනි ධ්‍යාන ලබ ගත හැක.

විදර්ශනා භාවනාව
විදර්ශනා භාවනවෙන් යමක මූලික ලක්ෂණය හෙවත් අනිත්‍ය භාවය තෙරුම් කර ගැනීමට හැකිවේ. අනිත්‍ය, දුක්‍ය, අනාත්ම යන ලක්ෂණ ප්‍රගුණ කරමින් යමක් විනිවිද දැකීමේ හැකියාව ප්‍රඤ්ඥාව වේ. විදර්ශනාව යනු ප්‍රඤ්ඥාව ලබා ගැනීමට ඉහත හැකියාව දියුනු කිරීමයි.

Monday, December 7, 2009

The unpredictability of conditional operator

If the 2nd and 3rd operands for conditional operator is not in the same type then better to avoid using it. E.g.

char x = 'X';
int i = 0;
System.out.print(true ? x : 0);
System.out.print(false ? i : x);
System.out.print(true ? new Integer(2) : new Float(3));

The specification for the conditional operator [JLS 15.25] has explained this. If both of the operands are not in the same object type then it will convert one of them into the more general one. For an example if operands and Integer and Float objects then it will convert Integer to Float. So as shown is above examples this will cause some unpredictable behaviors.