Decorator Pattern Hides Decoratee's Interfaces - c#

public interface IRender
{
void Render();
}
public interface IUpdate
{
void Update(float deltaTime);
}
I have classes that implement IRender, some of these also implement IUpdate.
By using the decorator pattern I am able to extend their Render method.
public abstract class Decorator: IRender
{
protected IRender decoratee;
public Decorator(IRender decoratee)
{
this.decoratee = decoratee;
}
public virtual Render()
{
decoratee.Render();
// add custom rendering code here.
}
}
The beauty of this is that I can created custom rendering behaviour by wrapping an object into multiple decorators like a babushka doll.
My problem is the fact that the IUpdate interface, as well as any other the decoratee implements, will now be hidden by the decorator. I have a number of Systems that accept a list of objects, and operates on them according to the interface they implement. The decorated class will only expose the IRender interface.
What is the cleanest way to get around this issue?

Related

Resolving multiple instances of interface implementation using Dry IOC

I have a scenario where there are multiple classes that implement the same interface. the consuming class is to get all the interface implementations as a list so that it can invoke method on all the instances.
public interface IDoSomething
{
void Do();
}
public class Dance : IDoSomething
{
public void Do() { }
}
public class Eat : IDoSomething
{
public void Do() { }
}
public class Person
{
public Person(IEnumerable<IDoSomething> actions)
{
foreach (IDoSomething ds in actions)
{
ds.Do();
}
}
}
How do I register the types so that class Person can resolve all the types that implement IDoSomething. This was possible with Unity, MEF and Spring.NET IOC containers. Trying to do the same with Dry IOC.
You just need to register multiple things as usual with the same interface and whatever implementations. Then inject IEnumerable of your interface, or you may use any other collection interface implemented by .NET array.
Example:
var container = new Container();
container.Register<IDoSomething, Dance>();
container.Register<IDoSomething, Eat>();
container.Register<Person, Person>();
For more information, see the documentation.

Interface and abstract class in this case

In case I want any class inherits/implements some methods which is better an interface or an abstract class contains these abstract methods only and acts as an interface. I know the difference between the interface and the abstract class well but in this case do the two have the same function or there are different something?
I think we can feel free to use one of them but still I take the side of interface because my aim is to enforce any class to implement these methods and it is the job of interface.
I agree an abstract class with no concrete behavior seems a little pointless so I would favour an interface.
Abstract classes are far more useful when bringing together some common behavior that cannot be overridden along with some elements that can eg) template methods
public abstract class Base
{
public void TemplateMethod()
{
AbstractMethod1();
AbstractMethod2();
}
public abstract void AbstractMethod1();
public abstract void AbstractMethod2();
}
public class Concrete : Base
{
public override void AbstractMethod1()
{
Console.Write("Override Abstract Method 1");
}
public override void AbstractMethod2()
{
Console.Write("Override Abstract Method 2");
}
}
public class Main
{
public Main()
{
var concrete = new Concrete();
concrete.TemplateMethod();
}
}

Declare method in interface

I have an interface INetworkAware and need to declare method which will forece every class to register for events
currently using prisms eventaggregator our implementation is the following.
protected override void SetupEvents()
{
RegisterForEvent<PatientSelected>(OnPatientSelected);
base.SetupEvents();
}
SetupEvents method is declared as virtual in ViewModelbase class. in out situation we want to have above mentioned INetworkAware interface and in addition to deriving from ViewModelBase if any class is interested in listening to network changes(network offline/online) and implement INetworkAware interface we want to have mechanism to force them to register for this event using same principals.
so for example if we create class
public class PatientInformationViewModel : ViewModelBase, INetworkAware
{
protected override void SetupEvents()
{
RegisterForEvent<PatientSelected>(OnPatientSelected);
base.SetupEvents();
}
INetworkAware.ListenForNetworkChange
{
RegisterForEvent<NetworkChangeEvent>(OnNetworkChange)
}
OnNetworkChange(NetworkChangeEvent networkstatus)
{
}
}
NetworkChangeEvent is a sample POCO class
INetworkAware.ListenForNetworkChange and OnNetworkChange(NetworkChangeEvent networkstatus) must be implemented in every viewmodel deriving from INetworkaware and with the same signature.
houw can we accomplish this scenario
You are almost on the right track. If you implement the interface on the base class and then declare your method as abstract in the base class that will force any extending (deriving) class to implement it's own version:
public abstract class ViewModelBase : INetworkAware
{
public abstract void SetupEvents();
}
public class PatientInformationViewModel : ViewModelBase
{
public override void SetupEvents()
{
//register for your events
}
}
Alternatively you can declare the method in the base class as virtual rather than abstract and provide a base implementation, and your derived classes can simply override this when necessary. I've used this pattern before myself and it is quite effective - just make sure you include an Unsubscribe() (or similar) on the interface as well.

Abstract class does not implement interface

I have an interface so class writers are forced to implement certain methods. I also want to allow some default implemented methods, so I create a abstract class. The problem is that all classes inherit from the base class so I have some helper functions in there.
I tried to write : IClass in with the abstract base, but I got an error that the base didn't implement the interface. Well of course because I want this abstract and to have the users implement those methods. As a return object if I use base I can't call the interface class methods. If I use the interface I can't access base methods.
How do I make it so I can have these helper classes and force users to implement certain methods?
Make sure methods in the base class have the same name as the interface, and they are public. Also, make them virtual so that subclasses can override them without hiding them.
interface IInterface {
void Do();
void Go();
}
abstract class ClassBase : IInterface {
public virtual void Do() {
// Default behaviour
}
public abstract void Go(); // No default behaviour
}
class ConcreteClass : ClassBase {
public override void Do() {
// Specialised behaviour
}
public override void Go() {
// ...
}
}
Move the interface methods into the abstract class and declare them abstract as well. By this, deriving classes are forced to implement them. If you want default behaviour, use abstract classes, if you want to only have the signature fixed, use an interface. Both concepts don't mix.
Having faced with the same problem recently, I've came up with a somewhat more elegant (to my mind) solution. It looks like:
public interface IInterface
{
void CommonMethod();
void SpecificMethod();
}
public abstract class CommonImpl
{
public void CommonMethod() // note: it isn't even virtual here!
{
Console.WriteLine("CommonImpl.CommonMethod()");
}
}
public class Concrete : CommonImpl, IInterface
{
void SpecificMethod()
{
Console.WriteLine("Concrete.SpecificMethod()");
}
}
Now, according to C# spec (13.4.4. Interface mapping), in the process of mapping IInterface on Concrete class, compiler will look up for CommonMethod in CommonImpl too, and it doesn't even have to be virtual in the base class!
The other significant advantage, compared to Mau's solution, is that you don't have to list every interface member in the abstract base class.

Implement common behaviour in alternative to abstract base classes?

In C#, I have a class hierarchy with a couple of abstract base classes near the top and a fair number of derived classes. A few these concrete classes have some common properties and methods that are implemented identically. It strikes me as wasteful and so one solution might be to implement this common behaviour in another abstract base class.
abstract class Control;
abstract class SquareControl: Control
{
public int SquarishProperty;
public void SquarishMethod();
};
class Window: SquareControl;
class Button: SquareControl;
However, what if several other classes in the hierarchy shared some other behaviour but also share something in common with one of the controls from another base class? Perhaps there are lots of areas of commonality. It would become impractical to model this with abstract base class implementation wouldn't it?
abstract class FlashableControl: Control
{
public int FlashyProperty;
public void FlashMethod();
};
class StatusBar: FlashableControl; // but it's also a bit square too, hmm...
So how do you go about sharing such implementations across classes without using base classes?
I imagine I want to delegate the implementaion of an interface to another class and have that class implement those properties and methods on behalf of the desired classes, so that to the user, the StatusBar and Window appear to support a standard interface, but under the covers it's something else that implements it.
I can visualise aggregating classes that implement this behaviour, but is this appropriate and are there any pitfalls? What are the alternatives?
Thanks
You can use a pattern like this:
public interface ICommonServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
public static class CommonServiceMethods
{
public static void DoSomething(this ICommonServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
All classes that implement ICommonServices now also get some free behavior via the extension method, which depends solely on those features exposed by all ICommonServices implementers. If you need access to base class functionality, you can put that in its own interface and have ICommonServices implement that interface as well. Now you can create 'default' extension functionality for interfaces without having to use multiple base classes.
EDIT
If you want some of these methods to be internal, you can modify the pattern like this:
public class MyObject : IServices
{
public string PublicProperty { get; private set; }
string IServices.SomeProperty { get; set; }
void IServices.SomeMethod(string param)
{
//Do something...
}
}
public interface IPublicServices
{
string PublicProperty { get; }
}
internal interface IServices : IPublicServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
internal static class ServiceMethods
{
public static void DoSomething(this IServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
Basically we're exposing both public and internal interfaces. Note that we implement the internal interface methods explicitly, so that the methods are not available for public consumption (since the public client can't get access to the interface type.) In this case, the helper extension methods are internal, relying on the internal interface, though you could also create public helper methods that rely on the public interface.
You could use 'has-a' instead of 'is-a' and delegate to an internal square control
class Window : Control, ISquareControl
{
private SquareControl square;
public void SquareOperation()
{
square.SquareOperation();
}
}
class SquareControl : Control, ISquareControl
{
public void SquareOperation()
{
// ...
}
}
One way is to use Interfaces and Base Classes.
Flashable would make a good Interface instead of a class.

Categories

Resources