Interfaces and Abstractions
Interface Polymorphism
Interface-typed collections can call different implementations through one type.
Interface Polymorphism
InterfacePolymorphism.cs
using System;
interface IFormatter
{
string Format(string value);
}
class UpperFormatter : IFormatter
{
public string Format(string value)
{
return value.ToUpper();
}
}
class BracketFormatter : IFormatter
{
public string Format(string value)
{
return "[" + value + "]";
}
}
class Program
{
static void Main()
{
string word = ;
IFormatter[] formatters = { new UpperFormatter(), new BracketFormatter() };
string summary = "";
foreach (IFormatter formatter in formatters)
{
if (summary.Length > 0)
{
summary += ",";
}
summary += formatter.Format(word);
}
Console.WriteLine($"word={word}");
Console.WriteLine($"summary={summary}");
}
}
using System;
interface IFormatter
{
string Format(string value);
}
class UpperFormatter : IFormatter
{
public string Format(string value)
{
return value.ToUpper();
}
}
class BracketFormatter : IFormatter
{
public string Format(string value)
{
return "[" + value + "]";
}
}
class Program
{
static void Main()
{
string word = ;
IFormatter[] formatters = { new UpperFormatter(), new BracketFormatter() };
string summary = "";
foreach (IFormatter formatter in formatters)
{
if (summary.Length > 0)
{
summary += ",";
}
summary += formatter.Format(word);
}
Console.WriteLine($"word={word}");
Console.WriteLine($"summary={summary}");
}
}
using System;
interface IFormatter
{
string Format(string value);
}
class UpperFormatter : IFormatter
{
public string Format(string value)
{
return value.ToUpper();
}
}
class BracketFormatter : IFormatter
{
public string Format(string value)
{
return "[" + value + "]";
}
}
class Program
{
static void Main()
{
string word = ;
IFormatter[] formatters = { new UpperFormatter(), new BracketFormatter() };
string summary = "";
foreach (IFormatter formatter in formatters)
{
if (summary.Length > 0)
{
summary += ",";
}
summary += formatter.Format(word);
}
Console.WriteLine($"word={word}");
Console.WriteLine($"summary={summary}");
}
}
interface polymorphism
Interface polymorphism dispatches to the actual object's implementation.