I want to do this in the right way to learn
I have a few classes which have only one method. For example:
public class RedColorText
{
public void AddRedColorText(string text)
{
//something here
}
}
public class WhiteColorText
{
public void AddWhiteColorText(string text)
{
//something here
}
}
Normally I could just create instance of each one of them based on the method I want to use but what if I got requirement to use only one class and call methods based on condition? Can I do this like below using constructor and switch? Or should I use something else like interfaces etc?
public class ColorText
{
public ColorText(enum condition, string text)
{
switch(condition)
{
case 1:
new RedColorText().AddRedColorText(text);
break;
case 2:
new WhiteColorText().AddWhiteColorText(text);
break;
}
}
}
7
You could always use an interface or an abstract class to define the contract where you have generalized behavior for the ColorText class, but you need to keep the method name the same (AddColorText)
public interface IColorText
{
public abstract void AddColorText(string text);
}
public class RedColorText : IColorText
{
public void AddColorText(string text)
{
//something here
}
}
public class WhiteColorText : IColorText
{
public void AddColorText(string text)
{
//something here
}
}
And then define a factory to create instances based on your type
public class ColorTextFactory
{
public static IColorText Create(enum condition)
{
switch(condition)
{
case 1:
return new RedColorText();
case 2:
return new WhiteColorText();
default :
return null;
}
}
}
If you want to create red ColorText class and add some text, following code can be used
var colorText = ColorTextFactory(1);
colorText.AddColorText("Red Color Text");