现在的位置: 首页 > 综合 > 正文

singleton模式 在软件开发中的运用

2013年07月01日 ⁄ 综合 ⁄ 共 2602字 ⁄ 字号 评论关闭

singleton模式可以保证这个类只有一个实例。

下面是这个模式的一种典型的写法

public class Singleton
{
    
protected Singleton() { }

    
private static Singleton instance;
    
private static object objLock = new object();
    
public static Singleton Instance
    
{
        
get
        
{
            
if (instance == null)
            
{
                
lock (objLock)
                
{
                    
if (instance == null)
                        instance 
= new Singleton();
                }

            }

            
return instance;
        }

    }

}

为了保证多线程环境下也只能有一个实例,所以在这里使用了锁(lock).如果每次获取的时候,都要将lock一次,这会对性能产生影

响,所以在lock之前,我们又进行了一次判断。
一般情况下,同一个运用程序都是使用同一个配置。所以配置就是一个Singleton的运用了。

public class Settings
    
{
        
private Settings() { }

        
private decimal _Tax = 0;
        
public decimal Tax
        
{
            
get return _Tax; }
            
set { _Tax = value; }
        }

    
private decimal _Discount = 0;
        
public decimal DefaultDiscount
        
{
            
get return _Discount; }
            
set { _Discount = value; }
        }



        
private void LoadSettings()
        
{
            SettingsProvider.Load(
this);  
        }


        
private static Settings instance = null;
        
private static object lockObj = new object();

        
public static Settings CurrentSettings
        
{
            
get
            
{
                
if (instance == null)
                
{
                    
lock (lockObj)
                    
{
                        
if (instance == null)
            
{    
                            instance 
= new Settings();
                instance.LoadSettings();
            }

                    }

                }

                
return instance;
            }

        }

    }

有些人习惯把配置写在数据库中,然后每次都读取一次数据库中的信息。在多用户环境下,或者类似WebForm运用程序,这样做浪费

了一次数据库连接。而且不能保证修改后的数据马上被运用。
有些业务逻辑需要使用单例模式。在我开发的一个餐厅管理软件中,当前的上下文中只能为一个客户点菜。这个时候就需要使用单例
模式了,而且使用了单例模式后,在别的类中就可以很放心的使用这个类的实例,降低了开发的难度。

private void Bind()
        
{
            
this.Reset();
            
if (currentButton != null)
                currentButton.BackColor 
= currentButton.Parent.BackColor;
            Dish currentDish 
= Context.CurrentContext.CurrentDish;
            
bool verdict = (currentDish != null);

            List
<Dish> lst = Paging.GetList(Context.CurrentContext.DishList, pageIndex, pageSize);
            
for (int i = 0; i < dishButtons.Length && i < lst.Count; i++)
            
{
                dishButtons[i].OrderDish 
= lst[i];
                
if (verdict && currentDish.Equals(lst[i]))
                
{
                    currentButton 
= dishButtons[i];
                    currentButton.BackColor 
= Color.SkyBlue;
                }

            }

            
this.Refresh();
        }

抱歉!评论已关闭.