Sharing a class between multiple forms

前端 未结 3 759
星月不相逢
星月不相逢 2021-01-23 05:39

I need help figuring this question out. I\'ve tried searching and I think I might have found a solution using a Singleton Design pattern, but want to make sure.

I have a

3条回答
  •  旧巷少年郎
    2021-01-23 06:11

    As you already said, this problem can be solved using the Singleton Design Pattern. Here is a small sample:

    public class MySingleton() {
        private static MySingleton instance = new MySingleton();
    
        //your attributes go here...
        private MySingleton() {
        //your logic goes here...
        }
    
        public static MySingleton getInstance() {
            return instance;
        }
    }
    

    Note that if your static instance will be used for multiple threads, your class should lock the shared resources. I'll let you a reference to Thread Safe Code

提交回复
热议问题