Work with separate classes, global / static class?

Say I have two separate classes: A and B.

I also have a C repository class that loads some information from a text file. For instance. It has methods loadLines() , addLine() , deleteLine() .

Ignoring data binding, how can I get A and B to work in the same class C. Is this possible?

For example, at the moment in class A and B formload I have:

 var classC = new C(); 

This causes re-execution. It would be much better if I could have one copy of class c to work with A or B.

edit: so using singleton when the class constructor is executed? - which class first creates it? and it happens only once when I accept it?

edit1: Using the singleton template implies that you should have only one of them in your design decision? could i have a few?

+4
source share
2 answers

You can use the Singleton template, or if you want to follow the path of the Injection implementation framework (which is much more than just creating singleons, but you should look into them), most DI containers have the ability to create only one instance of an object.

 class C { public static readonly C Instance = new C(); private C() { } } 

Then you will use it like:

 private void A_Load(object sender, EventArgs e) { var classC = C.Instance; } private void B_Load(object sender, EventArgs e) { var classC = C.Instance; } 
+6
source

If you want to have only one instance of class C, you can use a singleton pattern .

By creating a constructor in the C private class and having a public static method that takes care of giving you the right instance of C, you can make sure that A and B will always have the same instance:

 public class C { private static C instance; private C() { // do some stuff } public static C GetInstance() { if(instance==null) instance = new C(); return instance; } } 

In A and B you can:

 C theSameInstanceOfC = C.GetInstance(); 
+1
source

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


All Articles