享受代码,享受人生

SOA is an integration solution. SOA is message oriented first.
The Key character of SOA is loosely coupled. SOA is enriched
by creating composite apps.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

继承的Singleton模式的实现

Posted on 2005-03-26 22:30  idior  阅读(3542)  评论(11编辑  收藏  举报

在.net下实现Singleton,估计很多人都知道了.下面的代码可以说经典.

class MySingleton
{
    
private static MySingleton instance = new MySingleton();
    
public static MySingleton Instance get return instance; } }
}


但是继承的Singleton模式的实现的实现似乎不多见, 也没见过什么泛式.下面这个是我目前看到最好的.
供大家参考.其实其中的思想远不止实现Singleton模式, 它提供了一种方法可以使得父类可以调用尚不存在的子类中的静态方法.


using System;
using System.Reflection;

abstract class MySingleton
{
    
private static MySingleton instance = null;
    
private static readonly object padlock = new object();

    
public static MySingleton GetInstance()
    
{
        
lock (padlock)
        
{
            
if (instance == null)
                SetInstance(
typeof(ChildSingleton));

            
return instance;
        }
    
    }


    
public static void SetInstance(MySingleton instance)
    
{
        
lock (padlock)
        
{
            MySingleton.instance 
= instance;
        }

    }


    
public static void SetInstance(Type type)
    
{
        
if (type.IsSubclassOf(typeof(MySingleton)))
        
{
            MethodInfo register 
= type.GetMethod("Register", BindingFlags.Public | BindingFlags.Static);
            
if (register == null)
                
throw new InvalidOperationException("Instance must have a static Register method.");

            register.Invoke(
nullnull);
        }

    }


    
public virtual string Info get return this.GetType().FullName; } }
}


class ChildSingleton : MySingleton
{
    
private static ChildSingleton instance = new ChildSingleton();

    
private ChildSingleton()
    
{
    }


    
public static void Register()
    
{
        MySingleton.SetInstance(instance);
    }

}


class OtherSingleton : MySingleton
{
    
private static OtherSingleton instance = new OtherSingleton();
    
private OtherSingleton()
    
{
    }

    
    
public static void Register()
    
{
        MySingleton.SetInstance(instance);
    }

}


class EntryPoint
{
    
public static void Main(string[] args)
    
{
        MySingleton singleton 
= MySingleton.GetInstance();
        Console.WriteLine(singleton.Info);

        MySingleton.SetInstance(
typeof(OtherSingleton));
        singleton 
= MySingleton.GetInstance();
        Console.WriteLine(singleton.Info);
    }

}