Đỉnh NGUYỄN

life's a journey not a destination

Mẫu thiết kế Singleton động

Leave a comment


Với mẫu thiết kế Singleton động sau đây, mình có thể đối tượng là singleton hay non-singleton tại thời điểm chạy.

class MutableSingleton
{
    private static bool _singletonMode = true;
    private static MutableSingleton _instance = null;

    protected MutableSingleton()
    { 
    }

    public static MutableSingleton Instance
    {
        get
        {
            if (_instance == null || !IsSingleton)
                _instance = new MutableSingleton();

            return _instance;
        }
    }

    public static bool IsSingleton
    {
        get { return _singletonMode; }
        set { _singletonMode = value; }
    }
}

Có thể dùng phương thức GetHashCode() để kiểm tra 2 đối tượng cùng 1 thể hiện hay không

static void Main(string[] args)
{
    MutableSingleton singleton1 = MutableSingleton.Instance;
    MutableSingleton singleton2 = MutableSingleton.Instance;

    Console.WriteLine(singleton1.GetHashCode() + " equals " + singleton2.GetHashCode());

    MutableSingleton.IsSingleton = false;
    MutableSingleton nonSingleton1 = MutableSingleton.Instance;
    MutableSingleton nonSingleton2 = MutableSingleton.Instance;

    Console.WriteLine(nonSingleton1.GetHashCode() + " not equals " + nonSingleton2.GetHashCode());
}

Một kết quả

image

Advertisements

Author: dinhnn

Senior software developer, a technical leader. You can be reached at via email to dinhnguyenngoc@gmail.com, via my blog at dinhnguyenngoc.wordpress.com, and on Twitter @dinhnguyenngoc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s