如何正确传递Singleton

时间:2015-12-04 10:39:32

标签: c# oop

我有Singleton类可以从网上获取数据。我需要将这些数据传递给类FirstDerivedSecondDerived。在这种情况下是我的类Singleton反模式?使用DataSocket与FirstDerivedSecondDerived之间的聚合关系是否正常。也许它存在更好的面向对象解决方案?

namespace WpfApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new TestViewModel();
    }
}

public class TestViewModel
{
    public ObservableCollection<Base> Items { get; set; }
    public TestViewModel()
    {
        DataSocket.Instance.SendDataAsync();
        Items = new ObservableCollection<Base>();
        Items.Add(new FirstDerived(1, DataSocket.Instance));
        Items.Add(new SecondDerived(2, DataSocket.Instance));
    }
}
public abstract class Base
{

}

public class FirstDerived : Base, IDisposable
{
    public FirstDerived(int id, DataSocket socket)
    {
        socket.Client += ProcessDataFromSocket;
    }

    public void ProcessDataFromSocket(string arg)
    {
        Console.WriteLine("First Derived getting data: {0}", arg.ToString());
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

public class SecondDerived : Base, IDisposable
{
    public SecondDerived(int id, DataSocket socket)
    {
        DataSocket.Instance.Client += ProcessDataFromSocket;
    }
    public void ProcessDataFromSocket(string arg)
    {
        Console.WriteLine("Second Derived getting data: {0}", arg.ToString());
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

public sealed class DataSocket
{
    private static DataSocket instance;

    public delegate void Messages(string info);

    public event Messages Client;
    private DataSocket() 
    {

    }

    public void SendDataAsync()
    {
        Action Send = new Action(SendData);
        IAsyncResult result = Send.BeginInvoke(null,null);
    }

    public void SendData()
    {
        while(true)
        {
            if (Client != null)
            {
                System.Threading.Thread.Sleep(3000);
                Client("Test");
            }
        }
    }
    public static DataSocket Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new DataSocket();
            }
            return instance;
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

对我而言,DataSocket似乎是处理网络的类,因此任何与网络交互的代码都应该去那里。不要将它传递给构造函数。

相反,做一些更像这个序列的事情;

    DataSocket.Instance.SendDataAsync();
    Items = new ObservableCollection<Base>();

    var data1 = await DataSocket.ReadData();
    var data2 = await DataSocket.ReadData();

    Items.Add(new FirstDerived(1, data1));
    Items.Add(new SecondDerived(2, data2));

这样,您的类不依赖于全局的,不断变化的对象。

您可能还需要考虑某种lock语句,以确保代码的不同部分(例如,许多不同的同时Web请求)不会相互干扰。