I've inherited a large codebase and I'm trying to implement some new functionality into the framework. Basically, in order to do it the "right" way, I would have to modify the entire structure of the framework. since I'm not the guy who designed the framework, nor am I a mind reader, doing so probably isn't going to happen (although I would really love to redesign it all from scratch myself).
So in order to do what I want, I'm trying to implement a decorator pattern, of sorts. This answer from maliger suggests that what I'm doing below is perfectly valid. However, mono doesn't seem to like it; it complains that T cannot be derived from when I declare HappyDecorator
Please forgive the overly simplistic example, but it gets the point across.
public class HappyObject
{
public virtual void print()
{
Console.WriteLine ("I'm happy");
}
}
public class VeryHappyObject : HappyObject
{
public override void print()
{
Console.WriteLine ("I'm very happy");
}
public void LeapForJoy()
{
Console.WriteLine("Leaping For Joy!");
}
}
public class SuperHappyObject : VeryHappyObject
{
public override void print()
{
Console.WriteLine ("I'm super happy!");
}
public void DieOfLaughter()
{
Console.WriteLine("Me Dead!");
}
}
public class HappyDecorator<T> : T where T : HappyObject
{
public string SpecialFactor { get; set; }
public void printMe()
{
Console.WriteLine (SpecialFactor);
print();
}
}
class MainClass
{
public static void Main (string[] args)
{
HappyDecorator<HappyObject> obj = new HappyDecorator<HappyObject> ();
obj.SpecialFactor = Console.ReadLine();
obj.printMe();
}
}
You're typing HappyDecorator to T, but there's no instance of T to use inside that class.
public class HappyDecorator<T> where T : HappyObject
{
private readonly T _instance;
public HappyDecorator(T instance)
{
_instance = instance;
}
public string SpecialFactor { get; set; }
public void printMe()
{
Console.WriteLine(SpecialFactor);
_instance.print();
}
}
Another alternative is to structure it like this with a generic method instead of a generic class. It's not really a decorator then though:
public class HappyDecorator
{
public string SpecialFactor { get; set; }
public void printMe<T>(T instance) where T : HappyObject
{
Console.WriteLine(SpecialFactor);
instance.print();
}
}
And call like:
HappyDecorator obj = new HappyDecorator();
obj.SpecialFactor = Console.ReadLine();
obj.printMe(new HappyObject());
I think this is what you are trying to do:
public interface IhappyObject
{
void Print();
}
public class HappyObject : IhappyObject
{
private IhappyObject obj;
public HappyObject(IhappyObject obj)
{
this.obj = obj;
}
public void Print()
{
obj.Print();
}
}
public class VeryHappyObject : IhappyObject
{
public void Print()
{
Console.WriteLine("I'm very happy");
}
}
public class SuperHappyObject : IhappyObject
{
public void Print()
{
Console.WriteLine("I'm super happy!");
}
}
static void Main(string[] args)
{
HappyObject obj = new HappyObject(new SuperHappyObject());
obj.Print();
}
Related
I have an "inheritance-tree" which looks like this:
There is common code for the "TargetWithTeststand" and i would like to have a common code source. My only idea would be to use a separate static class and gather the methods which are common.
Another idea was to use a common interface with default methods, but this does not support override.
Do you have any better idea how to deal with such inheritance problems?
Here is a code example:
using System;
public class Program
{
public static void Main()
{
int deviceType = 1; // This value is read from a config file which can be changed
Device device = null;
switch (deviceType)
{
case 0:
device = new TargetWithTeststandDev1();
break;
case 1:
device = new TargetWithSimulationDev2();
break;
// [....]
}
device.ReadMotorSpeed();
device.UsePowerButton();
}
}
public abstract class Device
{
public virtual void UsePowerButton()
{
throw new NotImplementedException();
}
public virtual void ReadMotorSpeed()
{
throw new NotImplementedException();
}
}
public abstract class DeviceType1 : Device
{
public override void ReadMotorSpeed()
{
Console.WriteLine("Read motor speed with DeviceType1");
}
}
public abstract class DeviceType2 : Device
{
public override void ReadMotorSpeed()
{
Console.WriteLine("Read motor speed with DeviceType2");
}
}
public sealed class TargetWithTeststandDev1 : DeviceType1
{
public override void UsePowerButton()
{
Console.WriteLine("UsePowerButton on teststand with DeviceType1");
}
}
public sealed class TargetWithSimulationDev1 : DeviceType1
{
public override void UsePowerButton()
{
Console.WriteLine("UsePowerButton on teststand with DeviceType1");
}
}
public sealed class TargetWithTargetDev1 : DeviceType1
{
public override void UsePowerButton()
{
Console.WriteLine("UsePowerButton on Target with DeviceType1");
}
}
public sealed class TargetWithTeststandDev2 : DeviceType2
{
public override void UsePowerButton()
{
Console.WriteLine("UsePowerButton on Simulation with DeviceType2");
}
}
public sealed class TargetWithSimulationDev2 : DeviceType2
{
public override void UsePowerButton()
{
Console.WriteLine("UsePowerButton on Simulation with DeviceType2");
}
}
public sealed class TargetWithTargetDev2 : DeviceType2
{
public override void UsePowerButton()
{
Console.WriteLine("UsePowerButton on Target with DeviceType2");
}
}
You have literally drawn the diamond problem, One of the main reasons multiple inheritance is not supported.
The typical solution to this is to use composition instead of inheritance. I.e. gather all the common functions for a simulation in a separate class, that your SimulationDev1 and SimulationDev2 classes refer to, and any simulation operations would be delegated to this class.
An alternative would be to use interfaces and extension methods or default interface implementations to do more or less the same thing:
public interface ISimulation
{
int AProperty { get; }
}
public static class SimulationExtensions
{
public static int SomeCommonMethod(this ISimulation self, int b) => self.AProperty + b;
}
consider the following game code:
public class Player : MonoBehaviour {
public void UseItem(Item item) {
item.Use(this);
}
public void GetDrunk() {}
}
public class Item {
public WhatInterface[] itemUsages;
public void Use(Player player) {
foreach(var usage in itemUsages) {
usage.Execute(new ItemUsageArgs {itemUser = player, itemUsed = this})
}
}
}
public class GameManager : MonoBehaviour {
public Player mainCharacter;
public Item beer = new Item {itemUsages = new [] {
new TestConsole(),
new DamageFromItem (),
new DrunkFromITem ()
}}
private void Start() {
mainCharacter.Use(beer);
}
}
public class TestConsole : WhatInterface {
public void Execute(BaseArgs args) {
Debug.Log("function call executed");
}
}
public class DamageFromItem : WhatInterface {
public void Execute(ItemUsageArgs args) {
Debug.Log(args.itemUser + " take damage from " + args.itemUsed);
}
}
public class DrunkFromITem : WhatInterface {
public void Execute(ItemUsageArgs args) {
args.itemUser.GetDrunk();
}
}
public class BaseArgs {}
public class ItemUsageArgs : BaseArgs {
public Player itemUser;
public Item itemUsed;
}
so how to create interface type code that is suited for itemUsages?
Or do I wrongly create the design for this context?
Basically I'm trying strategy pattern so that item usages could be vary for every kind of item.
Things I tried, creating IItemUsage interface:
public interface IItemUsage {
void Execute(ItemUsageArgs args);
// but then anything that needs to implement this interface must use this method, even though it only needs BaseArgs.
// TestConsole class must conform to Execute(ItemUsageArgs) signature..
}
public class TestConsole : IItemUsage {
public void Execute(BaseArgs args) {
Debug.Log("function call executed");
}
// this won't compile
}
Assuming this is all of your code, you can make IItemUsage generic, and contravairant on the generic parameter.
public interface IItemUsage<in T> where T: BaseArgs {
void Execute(T args);
}
Have TestConsole implement IItemUsage<BaseArgs> and the other two classes implement IItemUsage<ItemUsageArgs>.
Now you can put instances of all three classes into an IItemUsage<ItemUsageArgs>[]:
IItemUsage<ItemUsageArgs>[] arr = new IItemUsage<ItemUsageArgs>[] {
new TestConsole(), new DamageFromItem(), new DrunkFromITem()
};
If you want to implement interface with some method, which has input arguments, that can be different types, you must define base argument class or use interface parameter instead.
For example:
public interface IItemUsage
{
void Execute(IItemUsageArgs args);
}
public interface IItemUsageArgs
{
//place public part of all ItemUsageArgs
}
public class ItemUsageArgs1 : IItemUsageArgs
{
}
public class ItemUsageArgs2 : IItemUsageArgs
{
}
public class ItemUsage1 :IItemUsage
{
public void Execute(ItemUsageArgs1 args)
{
//do you need
}
void IItemUsage.Execute(IItemUsageArgs args)
{
Execute(args as ItemUsageArgs1);
}
}
public class ItemUsage2 : IItemUsage
{
public void Execute(ItemUsageArgs2 args)
{
//do you need
}
void IItemUsage.Execute(IItemUsageArgs args)
{
Execute(args as ItemUsageArgs2);
}
}
I have a abstract base class, starting a timer which is common to all derived class,
public abstract class BaseClass
{
public virtual void Start() { _timer.Start(); }
}
Now I need to load different JSON configuration files for each derived class and create the file,
public class DerivedClass1 : BaseClass
{
private readonly List<config> configs = new List<config>();
public DerivedClass1()
{
configs = JsonSettings.GetConfigurations(#"./Configurations/1.json");
}
public override void Start()
{
base.Start();
foreach (var configuration in configs)
{
JsonSettings.CreateConfigFile(configuration);
}
}
}
public class DerivedClass2 : BaseClass
{
private readonly List<config> configs = new List<config>();
public DerivedClass2()
{
configs = JsonSettings.GetConfigurations(#"./Configurations/2.json");
}
public override void Start()
{
base.Start();
foreach (var configuration in configs)
{
JsonSettings.CreateConfigFile(configuration);
}
}
}
As I see there are lots of codes are duplicated in various derived class.
Can I move these piece of code as well as abstract base class or is there another way?
I think you could simplify your code to this:
public abstract class BaseClass
{
protected virtual List<config> configs { get; set; } = new List<config>();
public virtual void Start()
{
_timer.Start();
foreach (var configuration in configs)
{
JsonSettings.CreateConfigFile(configuration);
}
}
}
public class DerivedClass1 : BaseClass
{
public DerivedClass1()
{
configs = JsonSettings.GetConfigurations(#"./Configurations/1.json");
}
}
public class DerivedClass2 : BaseClass
{
public DerivedClass2()
{
configs = JsonSettings.GetConfigurations(#"./Configurations/2.json");
}
}
public interface BaseClass
{
void Start();
}
public interface IBaseClassUtil
{
void Start();
void setConfigs(List<config> configs);
}
public class BaseClassUtil : IBaseClassUtil
{
System.Timers.Timer _timer;
public List<config> _configs { get; set; } = new List<config>();
public void Start()
{
_timer.Start();
foreach (var configuration in _configs)
{
JsonSettings.CreateConfigFile(configuration);
}
}
public void setConfigs(List<config> configs)
{
_configs = configs;
}
}
public class DerivedClass1 : BaseClass
{
private IBaseClassUtil _baseUtility;
public DerivedClass1(IBaseClassUtil baseUtility)
{
_baseUtility = baseUtility;
_baseUtility.setConfigs( JsonSettings.GetConfigurations(#"./Configurations/1.json"));
}
public void Start()
{
_baseUtility.Start();
}
}
public class DerivedClass2 : BaseClass
{
private IBaseClassUtil _baseUtility;
public DerivedClass2(IBaseClassUtil baseUtility)
{
_baseUtility = baseUtility;
_baseUtility.setConfigs(JsonSettings.GetConfigurations(#"./Configurations/2.json"));
}
public void Start()
{
_baseUtility.Start();
}
}
This might be oveer engineered. Or might not suit ur current requirement.
Advantages would be
In future if you want u want to have different implementation for IBaseClassUtil it will be easier
And huge advantage would be this code is testable
If the classes differ by nothing but the configuration path, then you can have only one derived class that takes the path as a parameter in its ctor.
public DerivedClass(string configurationPath)
{
configs = JsonSettings.GetConfigurations(configurationPath);
}
Put please note that a decision on including inheritance in your architecture is not about code duplication, and by not giving us any information on the functions or even names of the classes (BaseClass and DerivedClass mean nothing. What do they represent? What's their function? Why are they related?) you give us no way of really helping you with your design.
actually i refactor some portion of code.
what i want to do is to initialize an object "Task" with an object "TaskArgument".
let s say "TaskArgument" is abstract and "Task" implements a method "OnEnterTask(TaskArgument args)" and is sealed (for some special behavior of the existing system, which is out of scope).
old code:
public sealed class Task : SomeSystemBaseTask {
private int accessMe;
private int meToo;
public void OnEnterTask(TaskArgument args) {
if (args is SimpleTaskArgument) {
accessMe = ((SimpleTaskArgument)args).uGotIt;
meeToo = 0;
} else if (args is ComplexTaskArgument) {
accessMe = ((ComplexTaskArgument)args).uGotItValue * ((ComplexTaskArgument)args).multiplier;
meToo = ((ComplexTaskArgument)args).multiplier - 1;
}
}
}
what would be the best practise avoid the typecheck?
my first stupud thought was:
public abstract class TaskArgument {
internal public abstract Initialize(Task args);
}
public class SimpleTaskArgument : TaskArgument {
public int uGotIt = 10;
internal public Initialize(Task task){
task.accessMe = uGotIt;
}
}
public class ComplexTaskArgument : TaskArgument {
public int uGotItValue = 10;
public int multiplier = 10;
internal public Initialize(Task task){
task.accessMe = uGotItValue*multiplier;
task.meToo = multiplier - 1;
}
}
public sealed class Task : SomeSystemBaseTask {
public int accessMe;
public int meToo;
public void OnEnterTask(TaskArgument args){
args.Initialize(this);
}
}
but then my "accessMe" is public and the "Initialize" method works only with "Task".
so i moved the typechecking to another place (in future).
is there any best practise or good design idea.
..."internal public"... mmhhmm?
another crazy idea was an inner class, but i dont like those and it make such a simple case more complex or don't:
public abstract class TaskArgument {
internal public abstract Initialize(ITaskWrapper wrapper);
}
public class SimpleTaskArgument : TaskArgument {
...
}
public class ComplexTaskArgument : TaskArgument {
...
}
public interface ITaskWrapper {
public int AccessIt { set; get; }
...
}
public sealed class Task : SomeSystemBaseTask {
private int accessMe;
...
class TaskWrapper : ITaskWrapper {
...
}
public void OnEnterTask(TaskArgument args){
args.Initialize(new TaskWrapper(this));
}
}
where is the best place for initialization when it is based on the given Type of the "TaskArgument"?
kindly excuse my bad english knowledge
greetings
mo
Use an interface.
public void OnEnterTask(TaskArgument args) {
if (args is SimpleTaskArgument) {
accessMe = ((SimpleTaskArgument)args).uGotIt;
} else if (args is ComplexTaskArgument) {
accessMe = ((ComplexTaskArgument)args).uGotItValue * ((ComplexTaskArgument)args).multiplier;
}
}
becomes
public void OnEnterTask(ITaskArgument args) {
accessMe = args.GetAccessMe();
}
Then you have your classes implement ITaskArgument and implement the method for each class. In general, when you're doing something like this:
accessMe = ((ComplexTaskArgument)args).uGotItValue * ((ComplexTaskArgument)args).multiplier;
where you're accessing multiple properties on an object to perform a calculation, it usually makes sense to push that logic into the class itself.
Sounds like you want to put the logic associated with each sub-class of TaskArgument onto that class. You could add an abstract method to TaskArgument called Calculate that has the sub-class specific calculation. That would remove the need for your if statements completely:
public class Task {
private int accessMe;
public void OnEnterTask(TaskArgument args)
{
accessMe = args.Calculate();
}
}
You would then put the multiplication or whatever is appropriate into each sub-class.
I would create a public interface, which only exposes the Intialize method. Do your calculations in your derived classes e.g.
public interface ITaskArgument
{
void Initialize(Task task);
}
public abstract class TaskArgument : ITaskArgument
{
protected int _value;
public class TaskArgument(int value)
{
_value = value;
}
public abstract void Initialize(Task task);
}
public class SimpleTaskArgument : TaskArgument, ITaskArgument
{
public SimpleTaskArgument(int value)
: base (value)
{
}
public override void Initialize(Task task)
{
task.AccessMe = _value;
}
}
public class ComplexTaskArgument : TaskArgument, ITaskArgument
{
private int _multiplier;
public ComplexTaskArgument(int value, int multiplier)
: base (value)
{
_multiplier = multiplier;
}
public override void Initialize(Task task)
{
task.AccessMe = _value * _multiplier;
}
}
public class Task
{
public Task()
{
}
public int AccessMe { get; set; }
public void OnEnterTask(ITaskArgument args)
{
args.Initialize(this);
}
}
example
SimpleTaskArgument simpleArgs = new SimpleTaskArgument(10);
ComplexTaskArgument complexArgs = new ComplexTaskArgument(10, 3);
Task task = new Task();
task.OnEnterTask(simpleArgs);
Console.WriteLine(task.AccessMe); // would display 10
task.OnEnterTask(complexArgs);
Console.WriteLine(task.AccessMe); // would display 30
OK, changed my answer a bit in light of the changing requirements appearing in the comments! (Sheesh, scope creep or what?!)
public class Task
{
public int Variable1 { get; internal set; }
public int Variable2 { get; internal set; }
public void OnEnterTask(ITaskInitializer initializer)
{
initializer.Initialize(this);
}
}
public interface ITaskInitializer
{
void Initialize(Task task);
}
public class SimpleTaskInitializer : ITaskInitializer
{
private int uGotIt = 10;
public void Initialize(Task task)
{
task.Variable1 = uGotIt;
}
}
public class ComplexTaskInitializer : ITaskInitializer
{
private int uGotIt = 10;
private int multiplier = 10;
public void Initialize(Task task)
{
task.Variable1 = uGotIt;
task.Variable2 = uGotIt * multiplier;
// etc - initialize task however required.
}
}
You could create overloads of Task as one option:
public class SimpleTask : Task
{
public override void EnterTask(TaskArgument arg)
{
var s = (SimpleTaskArgument)arg;
}
}
So each task type deals with an equivalent argument type. Or, you can move the logic to a TaskFactory with a static method that returns an int, and has the type checking argument there.
public static class TaskFactory
{
public static int GetVal(TaskArgument arg)
{
if (args is SimpleTaskArgument) {
return ((SimpleTaskArgument)args).uGotIt;
} else if (args is ComplexTaskArgument) {
return ((ComplexTaskArgument)args).uGotItValue * ((ComplexTaskArgument)args).multiplier;
}
}
}
Your interface implementation also would work; I wouldn't discount that... or define an abstract method within Taskargument, that each overrides to return the value.
HTH.
I want to create a class that can only be inherited, for that i know it should be made abstract. But now the problem is that i want to use functions of that class without making them static. How can i do that.
public abstract Class A
{
A()
{}
public void display()
{}
}
public Class B:A
{
base.A() // this is accessible
this.display() // this is not accessible if i dont make this function static above
}
Your example will not compile, you could consider something like this:
using System;
public abstract class A
{
protected A()
{
Console.WriteLine("Constructor A() called");
}
public void Display()
{
Console.WriteLine("A.Display() called");
}
}
public class B:A
{
public void UseDisplay()
{
Display();
}
}
public class Program
{
static void Main()
{
B b = new B();
b.UseDisplay();
Console.ReadLine();
}
}
Output:
Constructor A() called
A.Display() called
Note: Creating a new B() implicitly calls A(); I had to make the constructor of A protected to prevent this error:
"'A.A()' is inaccessible due to its protection level"
That's not true. You don't have to make Display() static; you can call it freely from the subclass. On the other hand, you can't call the constructor like that.
Maybe it's just an error in the example, but the real issue with the code you have is that you can't put method calls in the middle of your class definition.
Try this:
public abstract class A
{
public void Display(){}
}
public class B:A
{
public void SomethingThatCallsDisplay()
{
Display();
}
}
Here's how you can do this..
public abstract class A
{
public virtual void display() { }
}
public class B : A
{
public override void display()
{
base.display();
}
public void someothermethod()
{
this.display();
}
}