jeudi 24 janvier 2013

Design Patterns : Singleton Pattern

Posted on 12:26 by mabrouk


The Singleton pattern is very similar to creator pattern. This is very widely used pattern. Now a question might raise in the mind that why do we need this pattern and when it should be applied. Let us take a situation where you want to build a chess game. Where does the Singleton Pattern apply here?
chessboard is one, which is a square-checkered board with 64 squares arranged in an eight-by-eight grid. At the start, each player controls sixteen pieces: one king, one queen, two rooks, two knights, two bishops, and eight pawns. The object of the game is to checkmate  the opponent’s king, whereby the king is under immediate attack (in “check”) and there is no way to remove or defend it from attack on the next move.
Here your chessboard is Singleton class as its state should never change. It means even at nth movement, the board should hold all the records of pieces moved and its state. Let us now drive back to technical discussion.
The Singleton pattern allows a class to only one instance and it does provide a global access to the instance. How do we go on to make a Singleton class.
Sample code : SingletonClass.as
package com.sophiacom.as3.designpatterns.creational.singleton
{
public class SingletonClass
{
private static var _instance:SingletonClass;
public function SingletonClass(enforcer:SingletonEnforcer) {}
public static function getInstance():SingletonClass {
if (SingletonClass._instance == null) {
SingletonClass._instance = new SingletonClass(new SingletonEnforcer());
}
return SingletonClass._instance;
}
}
}
class SingletonEnforcer {}
First we are defining a private static property that holds the single instance of the class.
Then we go with a public static function that provides access to the single instance created.
A private constructor that restrict access in instantiating the class.
Oops ActionScript 3.0 does not have a private constructor! So, to do this, the solution is to force a parameter in the constructor while type isn’t accessible. Just with a class outer the package of the class but defined in the same file, because in ActionScript 3, only one class can be visible.

Liens

referencement google - navette aéroport paris - transport genève index adolescent
ExactSeek: Relevant Web Search