"Pieter" <pi****************@hotmail.coma écrit dans le message de news:
O9**************@TK2MSFTNGP06.phx.gbl...
| In my object oriented application (VB.NET 2.0, Windows Forms), a lot of
| objects are opened in different forms by a user. For instance (a stupid
| exemple, but it shows the easiest what's happening):
| -two instances of the Company-Object: MyCompany1 and MyCompany2, both of
| them are poiting to the same Company: for isntance the Company Microsoft.
|
| The problem is: if the user makes changes to one of the 2 instances, these
| changes are not automaticly made to the other instance. So what I somehow
| would need is a way that there is some local cache of the opened Business
| Objects, and in one is asked that is already opened, that a reference is
| given to the same object.
|
| This must definetly be something that is a common practice in OOP, but I
| can't find out how to do this?
My guess is that you are creating two instances of the same Company into two
separate references :
Company myCompany1 = new Company(...);
Company myCompany2 = new Company(...);
What you really want is to have two references to the same instance. This is
possibly easiest achieved by using a Class Factory rather than the
constructors of the classes, and is something that a lot of persistence
mechanisms use.
public static class CompanyFactory
{
private static Dictionary<int, WeakReferenceinstances = new
Dictionary<int, WeakReference>();
public static Company CreateCompany(int id)
{
if (instances.ContainsKey(id)
return (Company) instances[id].Target; // this will resurrect the
target if necessary
Company newCompany = new Company(id);
// populate new Company
WeakReference newInstance = new WeakReference(newCompany, true);
instances.Add(id, newInstance);
return newCompany;
}
}
Then this static method can be called from more than one place and will
always return the same instance. You also need to set up a strategy for
periodically sweeping this list and removing all WeakReferences whose
targets have been GCed.
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer