A design pattern provides a framework for building an application. Design patterns makes the design process cleaner and more efficient. You can use existing design patterns to make templates for your objects and allowing you to build software faster.
Se afișează postările cu eticheta Dessign Patern. Afișați toate postările
Se afișează postările cu eticheta Dessign Patern. Afișați toate postările
luni, 25 august 2014
Singleton pattern C# Example
Singleton is used to restrict instantiation of a class to one object. In this way we ensure that the class has only one instance.
When to use?
Usually singletons are used for centralized management and provide a global point of access to themselves.
Example
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
class Singleton
{
private static Singleton instance;
protected Singleton()
{
// protected constructor
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Singleton st = new Singleton(); Error 'WindowsFormsApplication1.Singleton.Singleton()' is inaccessible due to its protection level
Singleton st1 = Singleton.GetInstance();
Singleton st2 = Singleton.GetInstance(); // st2=st1
}
}
}
When to use?
Usually singletons are used for centralized management and provide a global point of access to themselves.
- logging
- configuration
- resources
Example
using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{class Singleton
{
private static Singleton instance;
protected Singleton()
{
// protected constructor
}
public static Singleton GetInstance()
{
if (instance == null)
{
lock (typeof(Singleton))
{
instance = new Singleton();
}
}
return instance;
}
}
public partial class Form1 : Form
{public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Singleton st = new Singleton(); Error 'WindowsFormsApplication1.Singleton.Singleton()' is inaccessible due to its protection level
Singleton st1 = Singleton.GetInstance();
Singleton st2 = Singleton.GetInstance(); // st2=st1
}
}
}
Abonați-vă la:
Postări (Atom)