Hi,
I have some classes that share between their methods and properties: for example class A call method of class B and both class must have common field/property
Common methods/property are several!
I thought of this approach
//------------------------------------------------------
// CLASS 'A'
//------------------------------------------------------
public class A
{
public A Instance{get{return this;}}
public IB b;
public float FieldA;
public void DoSomethingA()
{
FieldA = b.DoSomethingB ();
}
}
//------------------------------------------------------
// INTERFACE + CLASS 'B'
//------------------------------------------------------
public interface IB
{
B Instance{get;}
A a {get;set;}
float DoSomethingB();
}
public class B:IB
{
public B Instance{get{return this;}}
public A a {get;set;}
public virtual float DoSomethingB()
{
return a.FieldA * 0.5F;
}
}
//------------------------------------------------------
// CLASS B2
//------------------------------------------------------
public class B2:B
{
public override float DoSomethingB ()
{
return a.FieldA * 2.0F;
}
}
//------------------------------------------------------
// CLASS TEST
//------------------------------------------------------
public class test
{
public A a = new A();
public IB b;
public test (IB b)
{
this.b = b;
b.a = a.Instance;
a.b = b.Instance;
// other
}
}
public static void Main (string[] args)
{
test t = new test (new B());
t.a.FieldA = 5;
t.a.DoSomethingA();
Console.WriteLine (t.a.FieldA ); // return 2.5
test t1 = new test (new B2()); // return 10
t1.a.FieldA = 5;
t1.a.DoSomethingA();
Console.WriteLine (t1.a.FieldA );
}
Essentially in the class test pass the class instance A to the class B and vice versa (and thus also for future classes).
When i create a new instance of test i decide if use class B or B2 (trough interface).
This approach is correct or i'm in a wrong way?