GoF 设计模式 享元例子:
示例1:将一段文字的某一段内容转换为大写:
class TextFormatted
{
private string text;
private bool[] isFormatted;
public TextFormatted(string text)
{
this.text = text;
isFormatted = new bool[text.Length];
}
public void ToUpper(int start, int end)
{
for (int i = start; i < end; i++)
{
isFormatted[i] = true;
}
var s = text.Select((text,i) => isFormatted[i] ? char.ToUpper(text) : text).ToArray();
text = string.Join("",s);
}
public string Context => text;
}
class Program
{
static void Main(string[] args)
{
string text = "No matter the ending is perfect or not you cannot disappear from my world";
TextFormatted textFormatted = new TextFormatted(text);
textFormatted.ToUpper(3, 9);
Console.WriteLine(textFormatted.Context);
}
}
示例2:将一段文字的某一段内容颜色改变:
class TextFormatted
{
private string text;
private bool[] isFormatted;
public TextFormatted(string text)
{
this.text = text;
isFormatted = new bool[text.Length];
}
public void ToUpper(int start, int end)
{
for (int i = start; i < end; i++)
{
isFormatted[i] = true;
}
var s = text.Select((text,i) => isFormatted[i] ? char.ToUpper(text) : text).ToArray();
text = string.Join("",s);
}
public void OutPutAndChangeColor(int start, int end,ConsoleColor color=ConsoleColor.White)
{
for (int i = start; i < end; i++)
{
isFormatted[i] = true;
}
for (int i = 0; i < text.Length; i++)
{
if (isFormatted[i])
Console.ForegroundColor = color;
Console.Write(text[i]);
Console.ForegroundColor = ConsoleColor.White;
}
}
public string Context => text;
}
class Program
{
static void Main(string[] args)
{
string text = "No matter the ending is perfect or not you cannot disappear from my world";
TextFormatted textFormatted = new TextFormatted(text);
textFormatted.ToUpper(3, 9);//转换大写
textFormatted.OutPutAndChangeColor(3, 9,ConsoleColor.Red);//更换颜色
}
}