My Slider

Image Slider By Humayoun Kabir Lets Express our emotion with blog Email me at humayounk@ymail.com #htmlcaption

সোমবার, ২৭ আগস্ট, ২০১২

Singleton Design Pattern in C#

Singleton Design Pattern

Intent


  • Ensure a class has only one instance, and provide a global point of access to it.
  • Encapsulated “just-in-time initialization” or “initialization on first use”.

Problem


Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.

Discussion


Make the class of the single instance object responsible for creation, initialization, access, and enforcement. Declare the instance as a private static data member. Provide a public static member function that encapsulates all initialization code, and provides access to the instance.

The client calls the accessor function (using the class name and scope resolution operator) whenever a reference to the single instance is required.

Singleton should be considered only if all three of the following criteria are satisfied:

  • Ownership of the single instance cannot be reasonably assigned
  • Lazy initialization is desirable
  • Global access is not otherwise provided for

If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting.

The Singleton pattern can be extended to support access to an application-specific number of instances.

The “static member function accessor” approach will not support subclassing of the Singleton class. If subclassing is desired, refer to the discussion in the book.

Deleting a Singleton class/instance is a non-trivial design problem. See “To Kill A Singleton” by John Vlissides for a discussion.

Structure

Scheme of Singleton


Make the class of the single instance responsible for access and “initialization on first use”. The single instance is a private static attribute. The accessor function is a public static method.

Scheme of Singleton.

Example


The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, “The President of the United States” is a global point of access that identifies the person in the office.

Example of Singleton.

Check list


  1. Define a private static attribute in the “single instance” class.
  2. Define a public static accessor function in the class.
  3. Do “lazy initialization” (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.

Rules of thumb


  • Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
  • Facade objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
  • The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.
  • The Singleton design pattern is one of the most inappropriately used patterns. Singletons are intended to be used when a class must have exactly one instance, no more, no less. Designers frequently use Singletons in a misguided attempt to replace global variables. A Singleton is, for intents and purposes, a global variable. The Singleton does not do away with the global; it merely renames it.
  • When is Singleton unnecessary? Short answer: most of the time. Long answer: when it’s simpler to pass an object resource as a reference to the objects that need it, rather than letting objects access the resource globally. The real problem with Singletons is that they give you such a good excuse not to think carefully about the appropriate visibility of an object. Finding the right balance of exposure and protection for an object is critical for maintaining flexibility.
  • Our group had a bad habit of using global data, so I did a study group on Singleton. The next thing I know Singletons appeared everywhere and none of the problems related to global data went away. The answer to the global data question is not, “Make it a Singleton.” The answer is, “Why in the hell are you using global data?” Changing the name doesn’t change the problem. In fact, it may make it worse because it gives you the opportunity to say, “Well I’m not doing that, I’m doing this” – even though this and that are the same thing.

 

Ensures a class has only one instance and provide a global point of access to it.

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

using System;

  class MainApp
  {
 
    static void Main()
    {
      // Constructor is protected -- cannot use new 
      Singleton s1 = Singleton.Instance();
      Singleton s2 = Singleton.Instance();

      if (s1 == s2)
      {
        Console.WriteLine("Objects are the same instance");
      }

      // Wait for user 
      Console.Read();
    }
  }

  // "Singleton" 
  class Singleton
  {
    private static Singleton instance;

    // Note: Constructor is 'protected' 
    protected Singleton() 
    {
    }

    public static Singleton Instance()
    {
      // Use 'Lazy initialization' 
      if (instance == null)
      {
        instance = new Singleton();
      }

      return instance;
    }
  }
}

Why Design Patterns and How to Implement in C#(Part-1)

Design Patterns

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Uses of Design Patterns

Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.
Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn't require specifics tied to a particular problem.
In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.

Creational design patterns

This design patterns is all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.
  • Abstract Factory
    Creates an instance of several families of classes
  • Builder
    Separates object construction from its representation
  • Factory Method
    Creates an instance of several derived classes
  • Object Pool
    Avoid expensive acquisition and release of resources by recycling objects that are no longer in use
  • Prototype
    A fully initialized instance to be copied or cloned
  • Singleton
    A class of which only a single instance can exist

Structural design patterns

This design patterns is all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality.
  • Adapter
    Match interfaces of different classes
  • Bridge
    Separates an object’s interface from its implementation
  • Composite
    A tree structure of simple and composite objects
  • Decorator
    Add responsibilities to objects dynamically
  • Facade
    A single class that represents an entire subsystem
  • Flyweight
    A fine-grained instance used for efficient sharing
  • Private Class Data
    Restricts accessor/mutator access
  • Proxy
    An object representing another object

Behavioral design patterns

This design patterns is all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects.
  • Chain of responsibility
    A way of passing a request between a chain of objects
  • Command
    Encapsulate a command request as an object
  • Interpreter
    A way to include language elements in a program
  • Iterator
    Sequentially access the elements of a collection
  • Mediator
    Defines simplified communication between classes
  • Memento
    Capture and restore an object's internal state
  • Null Object
    Designed to act as a default value of an object
  • Observer
    A way of notifying change to a number of classes
  • State
    Alter an object's behavior when its state changes
  • Strategy
    Encapsulates an algorithm inside a class
  • Template method
    Defer the exact steps of an algorithm to a subclass
  • Visitor
    Defines a new operation to a class without change

Criticism

The concept of design patterns has been criticized by some in the field of computer science.

Targets the wrong problem

The need for patterns results from using computer languages or techniques with insufficient abstraction ability. Under ideal factoring, a concept should not be copied, but merely referenced. But if something is referenced instead of copied, then there is no "pattern" to label and catalog. Paul Graham writes in the essay Revenge of the Nerds.
Peter Norvig provides a similar argument. He demonstrates that 16 out of the 23 patterns in the Design Patterns book (which is primarily focused on C++) are simplified or eliminated (via direct language support) in Lisp or Dylan.

Lacks formal foundations

The study of design patterns has been excessively ad hoc, and some have argued that the concept sorely needs to be put on a more formal footing. At OOPSLA 1999, the Gang of Four were (with their full cooperation) subjected to a show trial, in which they were "charged" with numerous crimes against computer science. They were "convicted" by ⅔ of the "jurors" who attended the trial.

Leads to inefficient solutions

The idea of a design pattern is an attempt to standardize what are already accepted best practices. In principle this might appear to be beneficial, but in practice it often results in the unnecessary duplication of code. It is almost always a more efficient solution to use a well-factored implementation rather than a "just barely good enough" design pattern.

Does not differ significantly from other abstractions

Some authors allege that design patterns don't differ significantly from other forms of abstraction, and that the use of new terminology (borrowed from the architecture community) to describe existing phenomena in the field of programming is unnecessary. The Model-View-Controller paradigm is touted as an example of a "pattern" which predates the concept of "design patterns" by several years. It is further argued by some that the primary contribution of the Design Patterns community (and the Gang of Four book) was the use of Alexander's pattern language as a form of documentation; a practice which is often ignored in the literature.

 

শনিবার, ২৫ আগস্ট, ২০১২

জাভাস্ক্রিপ্ট টিউটরিয়াল (পর্ব-৩)

মাষ্টার্স পরীক্ষা আর ঈদের পর ফিরে এলাম আপনাদের মাঝে ।পোস্ট দিতে দেরি   হল বলে আন্তরিকভাবে দুঃখিত ।  আজ আমরা দেখবো কিভাবে এইচ টি এম এলের সাথে জাভাস্ক্রিপ্ট মানিক জোড়ের মত সম্পর্ক করে ডাইনামিক ওয়েব সাইট তৈরী করে । তাহলে দেখা যাক ,

HTML পেজে জাভামস্ক্রিপ্ট যুক্ত করার জন্য স্ক্রিপ্ট ট্যাগ ব্যবহার করা হয়।ঠিক এর অনুরূপে লেখা হয়।<script> </script>অংশের মধ্যে প্রয়োজনীয় এবং অন্যান্য কোড সমূহ রাখা হয়। অথবা এর মধ্যে জাভামস্ক্রিপ্ট যুক্ত করা হয়। হেডার এর মধ্যে রাখলে তাকে বলা হয় হেডার স্ক্রিপ্ট(header script) আর বডি এর মধ্যে করা হলে তাকে বলা হয় (body script) । সচরাচর এর মধ্যে বিভিন্ন ধরনের ফাংশন তৈরি করা হয় আর এর মধ্যে থেকেই  ঐ ফাংশনকে প্রয়োজনে কল করা হয়।
উদাহরনঃ
 <strong style="margin: 0px; padding: 0px; border: 0px; outline: none; color: rgb(0, 0, 0); ">www.amakeniye.blogspot.com</strong>

<html>
<head>



<title> www.amakeniye.blogspot.com
<
/title
>


<style>
body{background: #FFC}
</style>
<script type=”text/javascript”>
function myClick()
{
alert(“Welcome to JavaScript  World.”);
}

</script>
</head>
<body>

<button onclick=”myClick()”>Click Me
<
/button
>
</body>
</html>

একটা নোটপ্যাড open করে উপরের code টুকু লিখে file মেনু থেকে Save as এ ক্লিক করে File name: index.html , Save as type : All files, দিয়ে save করে index.html ফাইলটি আপনার পছন্দনীয় ব্রাউজার  দিয়ে open করলে নিচে প্রদর্শিত ছবির মত দেখাবে।
ব্লগে কোড অত্যন্ত ঝামেলার কাজ তাই কোড সঠিকভাবে বুঝা না গেলে আমি আন্তরিকভাবে দুঃখিত ।