How to "wrap" implementation in C#
Posted
by igor
on Stack Overflow
See other posts from Stack Overflow
or by igor
Published on 2010-03-19T14:45:43Z
Indexed on
2010/03/19
15:01 UTC
Read the original article
Hit count: 227
Hello,
I have these classes in C# (.NET Framework 3.5) described below:
public class Base
{
public int State {get; set;}
public virtual int Method1(){}
public virtual string Method2(){}
...
public virtual void Method10(){}
}
public class B: Base
{
// some implementation
}
public class Proxy: Base
{
private B _b;
public class Proxy(B b) { _b = b; }
public override int Method1()
{
if (State == Running)
return _b.Method1();
else
return base.Method1();
}
public override string Method2()
{
if (State == Running)
return _b.Method2();
else
return base.Method2();
}
public override void Method10()
{
if (State == Running)
_b.Method10();
else
base.Method10();
}
}
I want to get something this:
public Base GetStateDependentImplementation()
{
if (State == Running) // may be some other rule
return _b;
else
return base; // compile error
}
and my Proxy's implementation will be:
public class Proxy: Base
{
...
public override int Method1()
{
return GetStateDependentImplementation().Method1();
}
public override string Method2()
{
return GetStateDependentImplementation().Method2();
}
...
}
Of course, I can do this (aggregation of base implementation):
public RepeaterOfBase: Base // no any overrides, just inheritance
{ }
public class Proxy: Base
{
private B _b;
private RepeaterOfBase _Base;
public class Proxy(B b, RepeaterOfBase aBase)
{
_b = b;
_base = aBase;
}
}
...
public Base GetStateDependentImplementation()
{
if (State == Running)
return _b;
else
return _Base;
}
...
But instance of Base class is very huge and I have to avoid to have other additional copy in memory.
So I
- have to simplify my code
- have to "wrap" implementation
- have to avoid a code duplication
- have to avoid aggregation of any additional instance of Base class (duplication)
Is it possible to reach these goals?
© Stack Overflow or respective owner