以下是我现在这样做的方式:
public partial class App : Application
{
public static DataManager db;
public App()
{
DB.appUpdated = "Feb 1, 2017";
DB.appVersion = "0.1";
InitializeComponent();
MainPage = ..
}
public static DataManager DB
{
get
{
if (db == null)
{
db = new DataManager();
}
return db;
}
}
protected override void OnStart()
{
App.DB.InitData();
}
}
我想知道的是有更好的方法在Xamarin应用程序中启动类的单例实例吗?
答案 0 :(得分:2)
随着您的应用增长,如果您继续向App
课程添加静态属性,App
将变得非常混乱且无法管理。
我建议直接在DataManager
类中实现Singleton模式。
public class DataManager
{
static readonly Lazy<DataManager> _instanceHolder =
new Lazy<DataManager>(() => new DataManager());
...
//private constructor to prevent multiple instances of DataManager
private DataManager()
{
...
}
public static DataManager Instance => _instanceHolder.Value;
...
}
public partial class App : Application
{
public App()
{
DataManager.Instance.appUpdated = "Feb 1, 2017";
DataManager.Instance.appVersion = "0.1";
InitializeComponent();
MainPage = ..
}
protected override void OnStart()
{
DataManager.Instance.InitData();
}
}
我已在此示例Xamarin.Forms应用中实现了此Singleton模式: https://github.com/brminnick/XamConverter
例如,此类使用Singleton模式: https://github.com/brminnick/XamConverter/blob/master/Source/XamConverter/Models/UnitsOfMeasurement/Celsius.cs
这个ViewModel使用Singleton: https://github.com/brminnick/XamConverter/blob/master/Source/XamConverter/ViewModels/ConversionViewModel.cs