Design pattern suggestion needed - c#

I need a programming pattern but I couldn't figure out what it will be. I am not even sure if what I want is possible or not. Lets say I have a Class A and 10 class inherited from A. What I want is call the same method Method Print() implemented differently on each inherited class, but all of them need to repeat a same method of Class A.
Class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
}
Class A_1 : A
{
public override void Print()
{
StartingProcedure();
/// class specific print operation
EndingProcedure();
}
}
Class A_2 : A
{
public override void Print()
{
StartingProcedure();
/// class specific print operation
EndingProcedure();
}
}
As you see I dont want to keep writing StartingProcedure(); on each overridden Print method. I want to automate that procedure, when I inherit a new class from A I don't want to mind the Starting and Ending procedures, i want to just write the class specific print operation. Is there any pattern that will provide me this kind of a class behaviour?
BTW I work with C#

Class A
{
public void Print()
{
StartingProcedure();
SpecificPrint();
EndingProcedure();
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
protected virtual SpecificPrint() // could possibly be abstract
{
}
}
Class A_1 : A
{
public override void SpecificPrint()
{
/// class specific print operation
}
}
Class A_2 : A
{
public override void SpecificPrint()
{
/// class specific print operation
}
}

The pattern you are looking for in this case is the Template Pattern by Gang of Four (GoF).
Class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
Print();
}
protected void EndingProcedure()
{
/// something
}
}
usually you'll add another method called the Template Method:
/// Template Method
protected void Run()
{
StartingProcedure();
Print();
EndingProcedure();
}
class A_1 : A
{
public override void Print()
{
/// class specific print operation
}
public A_1()
{
base.Run();
}
}

As an alternative to Rik's answer, if you can change the class hierarchy, and you really don't want to call the base methods in the derived methods, you can use composition instead of inheritance to accomplish this. By using the decorator pattern, you can specify a print method that wraps the derived functions.
class PrintDecorator : A
{
private A wrappedA;
public PrintDecorator(A a)
{
wrappedA = a;
}
public virtual void Print()
{
//wrap the derived logic with the pre- and post- processing
StartingProcedure();
wrappedA.Print();
EndingProcedure();
}
}
class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
}
class A_1 : A
{
public override void Print()
{
/// class specific print operation
}
}
class A_2 : A
{
public override void Print()
{
/// class specific print operation
}
}
Example usage:
A dec = new PrintDecorator(new A_1());
dec.Print();

Related

design pattern for the case of abstract class with inheriting classes with empty implementation methods

Can you please recommend of a good practice pattern for the following scenario:
I have a base abstract class that defines the common behavior and two inheriting classes that each defines set of methods that differ the one implementation from the other.
Then in the creation code (let's say by configuration) I choose which implementation I desire for each case of the configuration setting and call "doWork", my issue is how to avoid the "empty" implementations in the inheriting classes in case the inheriting class chooses not to implement the method.
abstract class CommonParentClass{
public void doWork()
{
commonA();
commonB();
uniqueA();
uniqueB();
}
internal void commonA()
{
//do work which is same for inheriting classes
}
internal void commonB()
{
//do work which is same for inheriting classes
}
abstract void uniqueA();
abstract void uniqueB();
abstract void uniqueC();
}
class FirstChildClass:CommonParentClass
{
protected void uniqueA()
{
//implementation specific to first child
}
protected void uniqueB()
{
//EMPTY
}
protected void uniqueC()
{
//implementation specific to first child
}
}
class SecondChildClass:CommonParentClass
{
protected void uniqueA()
{
EMPTY
}
protected void uniqueB()
{
//implementation specific to second child
}
protected void uniqueC()
{
//implementation specific to second child
}
}
I have about 5/6 methods which are empty in one of the inheriting classes.
What Design Pattern should I use in order to overcome this and avoid code repetition?
Given that all these functions seem to have the same signature, you could conceivably use a list of Actions.
abstract class CommonParent
{
private readonly List<Action> _funcs = new List<Action>();
private void CommonA() { }
private void CommonB() { }
protected void AddAction(Action action) => _funcs.Add(action);
protected CommonParent()
{
_funcs.Add(CommonA);
_funcs.Add(CommonB);
}
internal void Execute()
{
foreach(Action action in _funcs)
action();
}
}
class FirstChildClass : CommonParent
{
private void UniqueA() { }
private void UniqueB() { }
private void UniqueC() { }
public FirstChildClass()
{
AddAction(UniqueA);
AddAction(UniqueB);
AddAction(UniqueC);
}
}
class SecondChildClass : CommonParent
{
private void UniqueD() { }
private void UniqueE() { }
private void UniqueF() { }
public SecondChildClass()
{
AddAction(UniqueD);
AddAction(UniqueE);
AddAction(UniqueF);
}
}

Introduce "Mandatory" Methods to Implementors of an Interface

The current implementation is pretty much aligns with a simple Strategy Design Pattern. There are multiple steps to be executed and these will be invoked provided by the following interface:
public interface ICommandStep
{
void Execute(CommandParameters cParams);
string StepName { get; }
}
Example implementor:
public class Step1 : ICommandStep {
public string StepName => "Initial Step";
public void Execute(CommandParameters cParams) {
// instructions
}
}
By now there many different classes implementing this interface, and I want to ensure all of them will have a pre and post step to execution. For example log state, params, StepName start and end.
How could I introduce a way to have protected virtual void PreExecute and protected virtual void PostExecute methods with common (overridable) logic and to make sure the method will always be invoked in this order:
1. PreExecute
2. Execute
3. PostExecute
Preferably without changing the Execute method in the implementor classes.
Introducing abstract class is possible.
You can declare base class and define overridable methods in needed order:
public interface ICommandStep
{
void Execute(CommandParameters cParams);
string StepName { get; }
}
public abstract class CommandBase : ICommandStep
{
public void Execute(CommandParameters cParams)
{
PreExecute();
ExecuteInternal(cParams);
PostExecute();
}
protected virtual void PostExecute()
{
}
protected virtual void ExecuteInternal(CommandParameters cParams)
{
}
protected virtual void PreExecute()
{
}
public abstract string StepName { get; }
}
public class Step1 : CommandBase
{
public override string StepName => "Initial Step";
protected override void ExecuteInternal(object cParams)
{
// instructions
}
}
Adding new methods to the interface will necessarily mean breaking the existing implementations. If implementation is optional then you should use an abstract class instead of an interface.
An alternative exists by adding a new interface and adding a runtime type-check in an extension method, like so:
public interface ICommandStep
{
void Execute(CommandParameters cParams);
string StepName { get; }
}
public interface ICommandStep2 : ICommandStep
{
void PreExecute()
void PostExecute()
}
public static class Extensions
{
public static void Execute2(this ICommandStep step, CommandParameters cParams)
{
if( step is ICommandStep2 step2 )
{
step2.PreExecute();
step2.Execute( cParams );
step2.PostExecute();
}
else
{
step2.Execute( cParams );
}
}
}
Usage:
ICommandStep[] steps = ...
foreach( ICommandStep step in steps )
{
step.Execute2( cmdParams );
}
I can think of 2 solutions:
Template Method pattern as proposed by Backs.
Decorator Pattern together with factory. Decorator pattern is great when you want to execute some code before/after call to other object. Factory is to ensure that each created object will be decorated.
Example implementation of 2.:
using System;
namespace ConsoleApplication6
{
/// <summary>
/// This is the component in Decorator Pattern
/// </summary>
public interface ICommandStep
{
void Execute(String cParams);
string StepName { get; }
}
/// <summary>
/// This is the concrete component in Decorator Pattern
/// </summary>
public class ConcreteStep1 : ICommandStep
{
public string StepName
{
get
{
return "1";
}
}
public void Execute(string cParams)
{
Console.WriteLine($"STEP {StepName}: EXECUTE");
}
}
/// <summary>
/// This is the decorator in Decorator Pattern
/// </summary>
public abstract class StepDecorator : ICommandStep
{
protected ICommandStep _commandStep;
public abstract string StepName
{
get;
}
public StepDecorator(ICommandStep commandStep)
{
this._commandStep = commandStep;
}
public abstract void Execute(string cParams);
}
/// <summary>
/// This is the concrete decorator in Decorator Pattern
/// </summary>
public class ConcreteStepDecorator : StepDecorator
{
public ConcreteStepDecorator(ICommandStep commandStep) : base(commandStep) { }
public override string StepName
{
get
{
return _commandStep.StepName;
}
}
public override void Execute(string cParams)
{
// You can do whatever you want before / after execution of command
Console.WriteLine($"STEP {_commandStep.StepName}: PRE EXECUTE");
_commandStep.Execute(cParams);
Console.WriteLine($"STEP {_commandStep.StepName}: POST EXECUTE");
}
}
/// <summary>
/// This is a Simple Factory. You encapsulate here creation of ICommandStep, so that it will always be decorated
/// </summary>
public class SimpleStepFactory
{
public ICommandStep createStep()
{
return new ConcreteStepDecorator(new ConcreteStep1());
}
}
class Program
{
static void Main(string[] args)
{
var step = new SimpleStepFactory().createStep();
step.Execute("params");
Console.ReadLine();
}
}
}
This solution has couple of advantages:
You can wrap your steps with many decorators, i.e. you can wrap step in decorator that shows it's name and wrap these two in another decorator that shows the parameters
You don't have to modify your steps, because all the extra work is handled by decorators

Overloading abstract generic methods in C#

I'm trying to implement a generic abstract method with a type constraint, then Implement it multiple times using different specified types.
public abstract class Ability
{
public abstract void BindToStation<T>(T station) where T : Station;
}
public class DashAbility : Ability
{
public override void BindToStation<NavStation>(NavStation station){ }
public override void BindToStation<CannonStation>(CannonStation station){ }
}
But I get an error which says the method has already been defined with the same paramater types.
I'm guessing that the compiler treats any generic paramater as the same in terms of the method signature, so these two methods look the same to it.
Still though, I'm wondering if theres a way to have generic method overloading using specific types.. ?
You can't do exactly what you want, but you can try an approach like this:
interface IBindableTo<T> where T : Station
{
void BindToStation(T station);
}
abstract class Ability
{
public abstract void BindToStation<T>(T station) where T : Station;
}
class DashAbility : Ability, IBindableTo<NavStation>, IBindableTo<CannonStation>
{
public override void BindToStation<T>(T station)
{
if (this is IBindableTo<T> binnder)
{
binnder.BindToStation(station);
return;
}
throw new NotSupportedException();
}
void IBindableTo<NavStation>.BindToStation(NavStation station)
{
...
}
void IBindableTo<CannonStation>.BindToStation(CannonStation station)
{
...
}
}
Hope this helps.
C# doesn't support specialization in that way, and neither does C++ easily when you want to specialize on runtime type.
But you can use polymorphism, so you can use double-dispatch:
public abstract class Station {
internal abstract void DashBindToStation();
}
public class NavStation : Station {
internal override void DashBindToStation() {
throw new NotImplementedException();
}
}
public class CannonStation : Station {
internal override void DashBindToStation() {
throw new NotImplementedException();
}
}
public abstract class Ability {
public abstract void BindToStation(Station station);
}
public class DashAbility : Ability {
public override void BindToStation(Station station) {
station.DashBindToStation();
}
}
Another possibility with C# is to use runtime dispatching using dynamic:
public abstract class Station {
}
public class NavStation : Station {
}
public class CannonStation : Station {
}
public abstract class Ability {
public abstract void BindToStation(Station station);
}
public class DashAbility : Ability {
public void BindToStation(NavStation station) {
}
public void BindToStation(CannonStation station) {
}
public override void BindToStation(Station station) {
BindToStation((dynamic)station);
}
}

Is it possible to have an override method call its abstract virtual method?

My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.
Imagine this:
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public virtual void Consume()
{
_consumed = true;
}
}
public class HealthyConsumable: AbstractConsumable
{
public override void Consume()
{
// Do something healthy and ...
base.Consume(); // Would like to avoid this...
}
}
public class PoisonousConsumable: AbstractConsumable
{
public override void Consume()
{
// Do something poisonous and ...
base.Consume(); // Would like to avoid this...
}
}
What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.
You could make Consume none virtual and within it you called another protected virtual (or abstract method) that can contain code that be change by sub classes. Consumers of your class can only call the public Consume method but this will intern call the sub class implementation specific code
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public void Consume()
{
_consumed = true;
InternalConsumerBehaviour();
}
protected virtual void InternalConsumeBehaviour()
{
//default do nothing could potentially mark this method abstract rather than virtual its up to you
}
}
public class HealthyConsumable: AbstractConsumable
{
protected override void InternalConsumeBehaviour()
{
// Do something healthy and ...
}
}
public class PoisonousConsumable: AbstractConsumable
{
protected override void InternalConsumeBehaviour()
{
// Do something poisonous and ...
}
}
If I get what you're asking right you could do something like this:
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public abstract void ConsumeEffects();
public void Consume()
{
this.ConsumeEffects();
_consumed = true;
}
}
public class HealthyConsumable: AbstractConsumable
{
public override void ConsumeEffects()
{
// Do something healthy and ...
// Consume will get called in the base
}
}
public class PoisonousConsumable: AbstractConsumable
{
public override void ConsumeEffects()
{
// Do something poisonous and ...
// Consume will get called in the base
}
}

"Base class params are not always used" code smell

Suppose you had such code:
public Base
{
abstract void Register();
}
public Registrator1: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
public Registrator2: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
But When you receive a new business rule asking you to write Registrator3 which actually registers based on some parameter and you change your code base to the next:
public Base
{
abstract void Register(externalParam);
}
public Registrator1: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate theUI
}
}
public Registrator2: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate the UI
}
}
public Registrator3: Base
{
override void Register(externalParam)
{
//uses a DDD - service passed in the params to populate the UI
}
}
But Registrator1 and Registrator2 do not need that param and the code becomes smelly. What are the ways to re-write this code?
You could use an object as a parameter here; which is commonly used in scenarios where the number of parameters can vary depending on the call being used.
struct RegistrationInfo
{
public static readonly RegistrationInfo Empty = new RegistrationInfo();
public string Username;
public string CustomerName;
public string Validity;
}
abstract class Base
{
public abstract void Register(RegistrationInfo info);
// If you want to retain the paramaterless call:
public void Register()
{
Register(RegistrationInfo.Empty);
}
}
class Registrar1 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.Username == null) throw new ArgumentNullException("info.Username");
}
}
class Registrar2 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.CustomerName == null) throw new ArgumentNullException("info.CustomerName");
}
}
This has the advantage that you don't need to change method parameters (which is breaking interface) each time a parameter is added. The usage also becomes somewhat self-documenting:
var r = new Registrar1();
r.Register(new RegistrationInfo(){ Username = "JimJoe" });
r.Register(RegistrationInfo.Empty);
It's like air freshener for this type of code smell, while it's still smelly; you can make it smell nicer.
Finally you can make the call-site cleaner by making it a params argument (this has a small amount of overhead); in all honesty though it is more smelly because it's a language hack. Finally you could improve it with generics:
class RegistrationInfo
{
}
class RegistrationInfo1 : RegistrationInfo
{
public string Arg;
}
class RegistrationInfo2 : RegistrationInfo
{
public int Arg;
}
interface IBase<in TRegistration>
where TRegistration : RegistrationInfo
{
void Register(TRegistration registration);
}
class Base : IBase<RegistrationInfo>
{
public void Register(RegistrationInfo registration)
{
}
}
class Registrar1 : IBase<RegistrationInfo1>
{
public void Register(RegistrationInfo1 arg)
{
}
}
class Registrar2 : IBase<RegistrationInfo2>
{
public void Register(RegistrationInfo2 arg)
{
}
}
Is it not possible to contain the logic for externalParam in Registrator3?
In other words, Registrator3 uses the param, then calls the unmodified parameterless base?
A lot really depends on where the logic belongs. If it is something intrinsic to the base, then put it in the base, and either overload the Register() function or supply a default value for the param so that sub classes don't need to provide it.
Assuming you want to reuse the registration logic from the base class, you could update the code as follows:
public class Base
{
public virtual void Register(object externalParam)
{
// base registration logic goes here
}
}
public class Registrator1: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator2: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator3: Base
{
public override void Register(object externalParam)
{
base.Register(externalParam);
// custom registration logic goes here
}
}
HTH,
Cosmin
EDIT: Updated code to compile.

Categories

Resources