Why do I see DataManager in some Xamarin apps configured with get?

My application is configured as follows:

public partial class App : Application
{

    public static DataManager db;

    public App()
    {
        InitializeComponent();
        MainPage = new MainPage();
    }

    public static DataManager DB
    {
        get
        {
            if (db == null)
            {
                db = new DataManager();
            }
            return db;
        }
    }

Can someone explain to me the advantage of setting up DataManager this way vs:

    public App()
    {
        InitializeComponent();
        MainPage = new MainPage();
        db = new DataManager();
    }
+4
source share
4 answers

Many people do not like static global variables. Instead, they try to replace them with concrete class examples.

What they really have to do is create an interface for each class and use dependency injection to provide the classes. This will then allow for unit testing and proper separation of problems. Using the MVVM pattern is also a good idea.

, .

+5

()

- > DataManager . DataManager , .

( )

- > DataManager . - . - .

+4

- . , .

:

public static DataManager db;

db public, - , .

DataManager Print(). , - :

  public App()
    {
        InitializeComponent();
        MainPage = new MainPage();
        db.Print();
    }

, db , , NullReferenceException .

, , Convenience strategy Constructor Optimisation strategy, , .

+3

,

public static App()
{
    db = new DataManager();
}

get-property. , , - ( ) DataManager, , . , , , DataManager, . , , , .

,

protected static DataManager db; 

singleton, .

+1

Source: https://habr.com/ru/post/1690504/


All Articles