This is a bit of an odd oop question. I want to create a set of objects (known at design time) that each have certain functions associated with them. I can either do this by giving my objects properties that can contain 'delegates':
public class StateTransition {
Func<bool> Condition { get; set; }
Action ActionToTake { get; set; }
Func<bool> VerifyActionWorked { get; set; }
}
StateTransition foo = new StateTransition {
Condition = () => {//...}
// etc
};
Alternatively I can use an abstract class and implement this for each object I want to create:
public abstract class StateTransition {
public abstract bool Condition();
public abstract void ActionToTake();
public abstract bool VerifyActionWorked();
}
class Foo : StateTransition {
public override bool Condition() {//...}
// etc
}
Foo f = new Foo();
I realise the practical consequences (creating at design time vs run time) of these two methods are quite different.
How can I choose which method is appropriate for my application?
A delegate is a method with a parameter and a return type. A delegate is a type that safely encapsulates a method. Delegates are object-oriented, type safe, and secure.
The main purpose of events is to prevent subscribers from interfering with each other. If you do not use events, you can: Replace other subscribers by reassigning delegate(instead of using the += operator), Clear all subscribers (by setting delegate to null), Broadcast to other subscribers by invoking the delegate.
Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
If you think of delegates as being similar to interface definitions for a specific type of method, you can start to see why delegates exist. They allow clients of our delegates to ignore all the details of their implementations - even their names!
How can I choose which method is appropriate for my application?
Does your application requires to define new transition objects that have additional different properties, or additional different methods ? Then making new subclasses, overrding methods, ("Polymorphism") is better.
Or.
Does your application requires to define transition objects that only change method behaviour ? Then Method Delegates or Methods Events are better.
Summary
Overriding Methods ("Polymorphism") is better when your application requires to add different features, like properties or methods, for different subclasses, not just changing the implementation of methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With