0

I'm wondering about the best solution (maybe pattern) to this problem: I have 2 classes that have reference to the same object

class A {
    ...
}
class X {
    A objectA;
}

class Y {
    A objectA;
}

the problem is how to keep these reference even when one class X or Y assingn new object. For example

class Y {
    A objectA;
    private void doSomething(){
          objectA = new A();  
    }
}

at this point the object X has deprecated reference, but I would like it to be aware of this change. Passing references to each other is unacceptable, so object X can not be aware of object Y.

EDIT: This pattern can exist in my appliaction more than once so I can't use Singleton

stasbar
  • 105
  • 1
  • 9

4 Answers4

0

Instead of keeping a direct reference to A in X and Y, store the object A in another class (for example ObjectStorage) which both X and Y can access.

sarathas
  • 25
  • 6
0

You can use the singleton design pattern.

https://fr.wikipedia.org/wiki/Singleton_(patron_de_conception)

Incepter
  • 2,711
  • 15
  • 33
0

If you need the obejct then why are you assigning the new object to the same reference. Why don't you create a new reference for new object.

Deepak Vajpayee
  • 348
  • 2
  • 4
  • 15
0

One of the key tenets of OOP is that you should try to create loosely coupled objects that interact with one another. In your example, both classes X and Y are tightly coupled to class A. This is not necessarily a bad thing, but it's always worth asking yourself whether both classes need a member variable (objectA). If the answer to that is yes, then there's a 2nd question is also worth asking: Do both class X and class Y need a reference to the same object instance of class A?

Quite often the answer to this question is no. In other words, it's not at all uncommon to see more than one class with a dependency on a common class, but there's no requirement that each of these need a reference to the same instance of that common class.

If the answer to this question is yes, however, then you have some options. A singleton is one option, but there are often other, better alternatives - Are there any viable alternatives to the GOF Singleton Pattern?

Michael Peacock
  • 2,011
  • 1
  • 11
  • 14