码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之单例模式

时间:2016-06-26 00:25:22      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

  单例模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点。

通常我们可以让一个全局变量使得一个对象被访问,但它不能防止你实例化多个对象。一个最好的办法是,让类自身负责保存它的唯一实例。这个类可以保证没有其他实例可以被创建,并且它可以提供一个访问该实例的方法。

下面的代码是通过两个button按钮来弹出小窗口,但是只能有一个小窗口被创建,不能出现点击一个按钮就创建一个,应该是点击第一个按钮创建一个小窗口,点击第二个时,就不创建了。

代码如下:

Form1:

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 单例模式双重锁定
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 fm = Form2.GetInstance(); ;
            fm.MdiParent = this;
            fm.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form2 fm = Form2.GetInstance(); ;
            fm.MdiParent = this;
            fm.Show();
        }

    }
    class Singleton
    {
       
    }
}

Form2(小窗口):

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 单例模式双重锁定
{
    public partial class Form2 : Form
    {
        private static Form2 instance;
        private static readonly object syncRoot = new object();
        private Form2()
        {
            InitializeComponent();
        } 
        public static Form2 GetInstance()
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Form2();
                    }
                }

            }
            return instance;
        }
        private void Form2_Load(object sender, EventArgs e)
        {

        }
    }
}

运行结果:

技术分享

设计模式之单例模式

标签:

原文地址:http://www.cnblogs.com/JsonZhangAA/p/5617143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!