What design pattern? - c#

I have a class A maintaining a list of objects class B.
But each object of class B can be referenced in any object of class A.
Class B also maintains a list of objects of class A where it is being referenced.
The program can and will create (several) objects of both class A and B 'at will' and also delete them.
If I use C# I can add and delete objects from both classes with following code
public class A
{
private List<B>ListOfObjects_B;
public bool Add(B Object)
{
bool bAdd = false;
if ((Object != null) && (ListOfObjects_B.IndexOf(B) <0))
{
ListOfObjects_B.Add(Object);
Object.Add(this);
bAdded = true;
}
return bAdded;
}
public bool Delete(B Object)
{
bool bDeleted = ListOfObjects_B.Remove(Object);
if (bDeleted == true) Object.Delete(this);
return bDeleted;
}
}
public class B
{
private List<A>ListOfObjects_A;
public bool Add(A Object)
{
bool bAdd = false;
if ((Object != null) && (ListOfObjects_A.IndexOf(A) <0))
{
ListOfObjects_A.Add(Object);
Object.Add(this);
bAdded = true;
}
return bAdded;
}
public bool Delete(A Object)
{
bool bDeleted = ListOfObjects_A.Remove(Object);
if (bDeleted == true) Object.Delete(this);
return bDeleted;
}
}
This will work as because of removing/adding the object to the ListOfObjects the SECOND time (by recursion) the function will be called it will fail to delete/add thereby avoiding an infinite loop.
But I don't like this code even though A and B do not know 'much' about the other class and just call a Delete/Add function.
I suppose this kind of problem is general and a design pattern exists for handling it in such a way that recursion can be avoided and updating both lists will be 'just better'.
What design pattern should I use? I would appreciate if some code would be added as well.

You can simplify thing by moving the "object association concern" into a dedicated class. Here's what I have in mind.
Define a class called AssociationTable. This class will maintain a list of pairs where each pair holds a reference to an A object and a reference to a B object.
Each A object (and each B object) will hold a reference to the AssociationTable object.
A.Add(B) will be implemented as table.add(this, b);
B.Add(A) will be implemented as table.add(a, this);
Deletion will be implemented as table.delete(this, b) or table.delete(a, this)
class Pair {
A a; B b;
Pair(A a, B b) { this.a = a; this.b = b; }
// Also override Equals(), HashCode()
}
class AssociationTalbe {
Set<Pair> pairs = ...;
void add(A a, B b) { pairs.add(new Pair(a, b)); }
void remove(A a, B b) { pairs.remove(new Pair(a, b)); }
}
class A {
AssociationTable table;
public A(AssociationTable t) { table = t; }
void add(B b) { table.add(this, b); }
void remove(B b) { table.remove(this, b); }
}
Edit:
The problem with this design is garbage collection. the table will hold references to objects thereby supressing their collection. In Java you could use a WeakReference object to overcome this issue. I am pretty sure there's something similar in the .Net world
Also, the table could be a singleton. I don't like singletons too much. In here, a singleton will make the A-B association unique across your program. This may be something that is undesirable but it depends on your concrete needs.
Finally, (just to put things in context) this design works the same way as Many-to-Many relationships in relational data bases.

I recently wrote a class to handle a similar problem. It is actually a simpler scenario (parent/child relationship with the children referencing their parent), but you could probably adapt it for your needs. The main difference is that the Parent property in my implementation should be replaced by a collection of parents.

About the only thing I can think of is using a Mediator pattern so that A doesn't add itself to B. Here's an example:
public class Mediator {
public void Add(A List, B Object) {
if(list.Add(Object)) {
object.Add(List);
}
}
public void Delete(A List, B Object) {
if(List.Delete(Object)) {
Object.Delete(List);
}
}
}
After this you would remove the lines of code which read "Object.Add(this);" and "if (bDeleted == true) Object.Delete(this);" This also has the benefit of reducing how many times each method is called as before object A's methods were being called twice since object B was also calling those methods on object A.
EDIT: Upon further review, I realized you were already using an Observer design pattern in a way. Object A is the observer and object B is the observable. Object A maintains a list of objects its observing and object B maintains a list of objects observing it. The only thing is I don't see any additional functionality, although there probably is some. Basically, Object B will notify all Object A's observing it that it's changed and all of those Object A's will ask for the change. If this is what you're looking for, then all you need to do is remove the lines "Object.Add(this);" and "if(bDeleted == true) Object.Delete(this);" from the B code as it is unnecessary.

Related

make a variable last for a call stack

I have a class that contains some fields. I need to compare instances of this class by value, so I defined GetHashCode and Equals accordingly. Because the class allows circular references, I need a mechanism to avoid infinite recursion (for a more detailed explanation see Value-equals and circular references: how to resolve infinite recursion?). I solved this problem by modifying my Equals method so that it keeps track of the comparisons done before:
class Foo
{
public string Name { get; set; }
public Foo Reference { get; set; }
public override int GetHashCode() { return Name.GetHashCode(); }
static HashSet<(Foo,Foo)> checkedPairs
= new HashSet<(Foo,Foo)>(ValuePairRefEqualityComparer<Foo>.Instance);
// using an equality comparer that compares corresponding items for reference;
// implementation here: https://stackoverflow.com/a/46589154/5333340
public override bool Equals(object obj)
{
Foo other = obj as Foo;
if (other == null)
return false;
if !(Name.Equals(other.Name))
return false;
if (checkedPairs.Contains((this,other)) || checkedPairs.Contains((other,this)))
return true;
checkedPairs.Add((this,other));
bool refsEqual = Reference.Equals(other.Reference);
checkedPairs.Clear();
return refsEqual;
}
}
Imagine the following code in the main method:
Foo foo1 = new Foo { Name = "foo" };
Foo foo2 = new Foo { Name = "foo" };
foo1.Reference = foo2;
foo2.Reference = foo1;
bool foo_equals_bar = foo1.Equals(foo2);
Console.WriteLine("foo_equals_bar = " + foo_equals_bar);
foo1.Equals(foo2) will store (foo1,foo2) in checkedPairs before it calls foo2.Equals(foo1). Inside foo2.Equals(foo1) it will be noticed that checkedPairs contains (foo1,foo2), and true will be returned. This result is transferred to the equal variable inside the call of foo1.Equals(foo2), then checkedPairs is cleared, and true is finally returned to the main method.
(Without utilizing checkedPairs inside Equals, there would be an infinite recursion jumping between foo1.Equals(foo2) and foo2.Equals(foo1).)
This works allright in my single-threaded, non-concurrent sandbox environment. However, I am only using a static field for checkedPairs because I don't know any other way to transfer the already collected items from one call of Equals to the next inside a call stack.
But with this approach I cannot use a multi-threaded or concurrent environment, where several Equals checks might run in parallel or in a mixed-up order (e.g. due to passing Equals as a delegate and invoking it later on instead of immediately).
Questions:
Will using a thread-static variable work? I am afraid not, because I can imagine that different Equals calls from the same call stack could still be executed on different threads (but I don't know).
Is there a way to make checkedPairs "call stack static"? So that each call stack gets its own copy of checkedPairs? Then for each new call stack, a new (empty) checkedPairs would be created, filled during recursion, and garbage collected after the recursion ends.
Thanks jdweng to point me to an easy solution that works for the particular code stated in the question:
Remove the checkedPairs field from the Foo class and replace the Equals method by this code:
public override bool Equals(object obj)
{
return MyEquals(obj, new HashSet<(Foo,Foo)>(ValuePairRefEqualityComparer<Foo>.Instance));
}
private bool MyEquals(object obj, HashSet<(Foo,Foo)> checkedPairs)
{
Foo other = obj as Foo;
if (other == null)
return false;
if (!Name.Equals(other.Name))
return false;
if (checkedPairs.Contains((this,other)) || checkedPairs.Contains((other,this)))
return true;
checkedPairs.Add((this,other));
return Reference.MyEquals(other.Reference, checkedItems);
}
However, this approach is not going to work in general. Take for example the classes from this question: Value-equals and circular references: how to resolve infinite recursion?, and imagine I defined MyEquals analogously there for both Club and Person. Since MyEquals cannot be called from outside the class (I want it private), there will still be infinite recursion. E.g. when Person.MyEquals is called, it will call FavouriteInstitution.Equals inside, but it should redirect to FavouriteInstitution.MyEquals somehow(with a possibly already filled checkedPairs!). Also, Members.SetEquals(other.Members) will redirect to Person.Equals instead of Person.MyEquals.

Is this one of them circular references?

I want to add an easily accessible helper class to my asp mvc page. I created a class called Repositories. It has a static property "Current" which does the following:
public static readonly Repositories Current
{
get
{
if(HttpContext.Current.Items["Repositories"] == null)
HttpContext.Current.Items["Repositories"] = new Repositories(HttpContext.Current);
return (Repositories)HttpContext.Current.Items["Repositories"];
}
}
The point is that the class has static helper functions that use the current instance of the class (tied to current httpcontext). The helper functions do all kinds of stuff, the reason I wanted to organize them like this is because it makes for a nicer looking code in the controllers and i have potential access to all database repositories (the actual handle objects are created only if accessed in this context though).
Anyway, as you can see, the constructor takes a HttpContext as an argument, which is then stored in a private class field so I'd have less to type. This means that the Repositories class instance refers to HttpContext class instance and vice-versa. When the HttpContext is dropped, does this mean that it still sticks around in the memory, being preserved by a circular-reference by the Repositories instance?
An "orphaned" circular reference doesn't force objects to stay around in memory.
If you do this:
class A
{
public B b;
~A()
{
Console.WriteLine("COLLECTED A!");
}
}
class B
{
public A a;
~B()
{
Console.WriteLine("COLLECTED B!");
}
}
and run this code:
var a = new A();
var b = new B();
a.b = b;
b.a = a;
a = null;
b = null;
GC.Collect();
Both instances can (and will) be garbage collected. You will get something similar to the following output:
COLLECTED B!
COLLECTED A!

Dispose static variable on page reload or use something else

I don't usually code C#, when i do, i suck
I have parent Class and two derived class. both derived class share an expensive calculation which slightly differ for second one. I am trying to avoid calculate one.
However, i want
interface ICalculator
{
double getValue(int id);
void setContext(int c);
}
abstract class CalculatorBase: ICalculator
{
internal static Dictionary<int, double> output = null;
internal void loadData()
{
//load data
}
internal computeAll()
{
//do expenseive calculation and set output
output = something
}
double abstract getValue(int id);
void abstract setContext(int c);
}
class ChildCalculator1 : CalculatorBase
{
override void setContext(int c)
{
if (output !=null)
return;
loadData();
computeAll();
}
public ovverride getValue(int id)
{
return output[id];
}
}
class ChildCalculator2 : CalculatorBase
{
override void setContext(int c)
{
if (output !=null)
return;
loadData();
computeAll();
}
public ovverride getValue(int id)
{
return output[id] -1;
}
}
requirements:
if ChildCalculator1 or ChildCalculator or both (one after another) is called, computeAll will be computed once.
However, if you reload this page i want to calculate once. This means i want to calculate once every pageload
Question: How can i access parent properties (output) from two different child instance (ChildCalculator1, ChildCalculator) and if you reload the page, that proproperty (output) will be recalculated? Currently I made output as static but this doesnt change when i reload the page.
Static variable might not be the right thing as they survive through out the application not page load. How can i dispose after pageload is done or anything else you can suggest?
Your code isn't so bad... but it could definitely be better. :)
You are correct that the static dictionary will not get garbage collected. (In C# the Garbage Collector free's unused memory) You need all instances of calculator to share your dictionary and you want to dispose of it when you are done. You could implement a little factory that builds the calculators and gives them all a single instance of the dictionary. A very simple way to do this however is just to manually manage the static dictionary.
If you add the following method in CalculatorBase
public static void DoneWithCalculations()
{
// By removing your static reference to your dictionary you
// allow the GC to free the memory.
output = null;
}
You can then call this static method when you are all done with your calculators (for instance at the end of PageLoad) like so...
CalculatorBase.DoneWithCalculations();
This will do what you need and doesn't force you to work in C# more than you have to. :)

Multiple inheritance problem in C#

This question came to my mind while I
am reading the post Why doesn't C#
support multiple inheritance?
from MSDN Blog.
At first look at the following code:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class A
{
int num;
public A()
{
num = 0;
}
public A(int x)
{
num = x;
}
public override int GetHashCode()
{
return num + base.GetHashCode();
}
}
class B : A
{
int num;
public B()
{
num = 0;
}
public B(int x)
{
num = x;
}
public override int GetHashCode()
{
return num + base.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
Console.Write(a.GetHashCode() + " " + b.GetHashCode());
Console.Read();
}
}
}
Object class is the ultimate base class of all classes. So it is the base class of A and B both in my program and also make A as a base class of B. So B has now two base class, one is A and another is Object. I override one method GetHashCode() of Object Class in class A and B both. But in class B, base.GetHashCode() method returns the return value of GetHashCode() method of class A. But I want this value from Object class. How can I get that?
B has only one base class, and that is A. A has one base class, and that is object. There is no multiple inheritance; object is only inherited by classes that don’t already inherit from something else.
If you still think you need to call object.GetHashCode(), there is a very hacky workaround to do this in the question How to invoke (non virtually) the original implementation of a virtual method?.
You could write a protected instance method in class A that exposes GetHashCode() from Object. Then call that protected method in class B.
No Class B merely has one base class, class A.
To understand, class A really should be written as:
class A : Object
But since that is required, it can be left off.
This may help you: http://itpian.com/Coding/5191-cant-v-have-Multiple-Inheritances-in-C-sharp---------.aspx
Yes, this doesn't relate to multiple inheritance at all (incidentally, I miss private inheritance more than multiple inheritance). This question is also quite a horrible thing to think about.
If you have control of class A, then fine:
class A
{
/*elide the stuff you already have*/
protected int GetBaseHashCode()
{
return base.GetHashCode();
}
}
class A : B
{
/*elide stuff already in example*/
public override int GetHashCode()
{
return num + GetBaseHashCode();
}
}
If you do not:
public class B : A
{
private static readonly DynamicMethod GRANDPARENT_GET_HASH_CODE;
static B()
{
MethodInfo gpGHC = typeof(object).GetMethod("GetHashCode", BindingFlags.Public | BindingFlags.Instance);
GRANDPARENT_GET_HASH_CODE = new DynamicMethod("grandParentGHC", typeof(int), new Type[] { typeof(object) }, typeof(object));
ILGenerator il = GRANDPARENT_GET_HASH_CODE.GetILGenerator();
il.Emit(OpCodes.Ldarg, 0);
il.EmitCall(OpCodes.Call, gpGHC, null);
il.Emit(OpCodes.Ret);
}
private int num;
public B()
{
num = 0;
}
public B(int x)
{
num = x;
}
public override int GetHashCode()
{
return num + (int)GRANDPARENT_GET_HASH_CODE.Invoke(null, new object[]{this});
}
}
Frankly, I would put that code in the category of "let us never speak of it again". I assume this is relating to some more general principle, since the hashcodes here are useless anyway, but I'm not sure what that more general principle is. Certainly it can sometimes be annoying when something is hidden from deriving classes we want to get at, but it can be much worse when the opposite happens.
Back in the days of VB6, coders in that language would often have to do rather nasty stuff involving getting the memory address of the v-table used for virtual call lookup, altering the memory protection, and then tweaking the bytes stored there by hand, because in "protecting" users from implementation details they kept some vital things away from them (you could not create enumerators without this technique, only pass on those for other objects).
Thank goodness we are not "protected" to that extent in C#. If I ever have to write code like the answer I gave above for a real project, I'm going to need a few drinks to recover later that evening.
Getting a hash of the base Object class is irrelevant to the purpose of the method. The whole point of GetHashCode() is to generate a unique (as possible) identity value based on the specific type and state of the object.
The GetHashCode() method uses a default hashing algorithm that can be used to determine instance identity and uniqueness, though uniqueness is not guaranteed. The default algorithm uses the state of the object to generate the hash.
More information: http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
I'm afraid you are mixing normal inheritance with multiple inheritance. Multiple inheritance meand that you have 3 classes A is subclass of B and C but neither B is subclass of C nor C is subclass of B.
Normal inheritance does allow chaining like A is subclass of B which is subclass of C. If you call method it can walk through the classes and check which method to call (in reality it does not check classes one by one). Here B is subclass of A which is subclass of Object. Object happens to have (virtual) method GetHashCode - by overloading it in subclass. The Object method is hidden and (without tricks) cannot be used.
You should consider an alternative to calling Object.GetHashCode(). Here's why (from MSDN Library):
The default implementation of the
GetHashCode method does not guarantee
unique return values for different
objects. Furthermore, the .NET
Framework does not guarantee the
default implementation of the
GetHashCode method, and the value it
returns will be the same between
different versions of the .NET
Framework. Consequently, the default
implementation of this method must not
be used as a unique object identifier
for hashing purposes.

Initializing constructor from stored cache in C#

I'm not sure exactly how to describe this question, but here goes. I've got a class hierarchy of objects that are mapped in a SQLite database. I've already got all the non-trivial code written that communicates between the .NET objects and the database.
I've got a base interface as follows:
public interface IBackendObject
{
void Read(int id);
void Refresh();
void Save();
void Delete();
}
This is the basic CRUD operations on any object. I've then implemented a base class that encapsulates much of the functionality.
public abstract class ABackendObject : IBackendObject
{
protected ABackendObject() { } // constructor used to instantiate new objects
protected ABackendObject(int id) { Read(id); } // constructor used to load object
public void Read(int id) { ... } // implemented here is the DB code
}
Now, finally, I have my concrete child objects, each of which have their own tables in the database:
public class ChildObject : ABackendObject
{
public ChildObject() : base() { }
public ChildObject(int id) : base(id) { }
}
This works fine for all my purposes so far. The child has several callback methods that are used by the base class to instantiate the data properly.
I now want to make this slightly efficient. For example, in the following code:
public void SomeFunction1()
{
ChildObject obj = new ChildObject(1);
obj.Property1 = "blah!";
obj.Save();
}
public void SomeFunction2()
{
ChildObject obj = new ChildObject(1);
obj.Property2 = "blah!";
obj.Save();
}
In this case, I'll be constructing two completely new memory instantiations and depending on the order of SomeFunction1 and SomeFunction2 being called, either Property1 or Property2 may not be saved. What I want to achieve is a way for both these instantiations to somehow point to the same memory location--I don't think that will be possible if I'm using the "new" keyword, so I was looking for hints as to how to proceed.
Ideally, I'd want to store a cache of all loaded objects in my ABackendObject class and return memory references to the already loaded objects when requested, or load the object from memory if it doesn't already exist and add it to the cache. I've got a lot of code that is already using this framework, so I'm of course going to have to change a lot of stuff to get this working, but I just wanted some tips as to how to proceed.
Thanks!
If you want to store a "cache" of loaded objects, you could easily just have each type maintain a Dictionary<int, IBackendObject> which holds loaded objects, keyed by their ID.
Instead of using a constructor, build a factory method that checks the cache:
public abstract class ABackendObject<T> where T : class
{
public T LoadFromDB(int id) {
T obj = this.CheckCache(id);
if (obj == null)
{
obj = this.Read(id); // Load the object
this.SaveToCache(id, obj);
}
return obj;
}
}
If you make your base class generic, and Read virtual, you should be able to provide most of this functionality without much code duplication.
What you want is an object factory. Make the ChildObject constructor private, then write a static method ChildObject.Create(int index) which returns a ChildObject, but which internally ensures that different calls with the same index return the same object. For simple cases, a simple static hash of index => object will be sufficient.
If you're using .NET Framework 4, you may want to have a look at the System.Runtime.Caching namespace, which gives you a pretty powerful cache architecture.
http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx
Sounds perfect for a reference count like this...
#region Begin/End Update
int refcount = 0;
ChildObject record;
protected ChildObject ActiveRecord
{
get
{
return record;
}
set
{
record = value;
}
}
public void BeginUpdate()
{
if (count == 0)
{
ActiveRecord = new ChildObject(1);
}
Interlocked.Increment(ref refcount);
}
public void EndUpdate()
{
int count = Interlocked.Decrement(ref refcount);
if (count == 0)
{
ActiveRecord.Save();
}
}
#endregion
#region operations
public void SomeFunction1()
{
BeginUpdate();
try
{
ActiveRecord.Property1 = "blah!";
}
finally
{
EndUpdate();
}
}
public void SomeFunction2()
{
BeginUpdate();
try
{
ActiveRecord.Property2 = "blah!";
}
finally
{
EndUpdate();
}
}
public void SomeFunction2()
{
BeginUpdate();
try
{
SomeFunction1();
SomeFunction2();
}
finally
{
EndUpdate();
}
}
#endregion
I think your on the right track more or less. You can either create a factory which creates your child objects (and can track "live" instances), or you can keep track of instances which have been saved, so that when you call your Save method it recognizes that your first instance of ChildObject is the same as your second instance of ChildObject and does a deep copy of the data from the second instance over to the first. Both of these are fairly non-trivial from a coding standpoint, and both probably involve overriding the equality methods on your entities. I tend to think that using the first approach would be less likely to cause errors.
One additional option would be to use an existing Obect-Relational mapping package like NHibernate or Entity Framework to do your mapping between objects and your database. I know NHibernate supports Sqlite, and in my experience tends to be the one that requires the least amount of change to your entity structures. Going that route you get the benefit of the ORM layer tracking instances for you (and generating SQL for you), plus you would probably get some more advanced features your current data access code may not have. The downside is that these frameworks tend to have a learning curve associated with them, and depending on which you go with there could be a not insignificant impact on the rest of your code. So it would be worth weighing the benefits against the cost of learning the framework and converting your code to use the API.

Categories

Resources