通常建立一些管理物件
為了統一控管
不想被多個物件操作
我們可以利用 sealed class 的關鍵字
禁止其他類別繼承 sealed class
藉此操作物件內的資料
以下是 sealed class 的用法
sealed public class S3Mgr
{
....
}
只要繼承 S3Mgr 就會編譯錯誤
sealed public class S3Mgr
{
....
}
// A.cs 檔
partial class Program
{
public A _a = new A();
....
}
// B.cs 檔
partial class Program
{
public B _a = new B();
....
}
/// <summary>
/// 圖形抽像類
/// </summary>
public abstract class Graphics
{
public string Name { get; set; }
public Graphics(string name)
{
this.Name = name;
}
public abstract void Draw();
public abstract void Add(Graphics g);
public abstract void Remove(Graphics g);
}
/// <summary>
/// 簡單圖形類——線
/// </summary>
public class Line : Graphics
{
public Line(string name)
: base(name)
{ }
// 重寫父類抽像方法
public override void Draw()
{
Console.WriteLine("畫線:" + Name);
}
public override void Add(Graphics g)
{
throw new Exception("不能向簡單圖形Line添加其他圖形");
}
public override void Remove(Graphics g)
{
throw new Exception("不能向簡單圖形Line移除其他圖形");
}
}
/// <summary>
/// 簡單圖形類——圓
/// </summary>
public class Circle : Graphics
{
public Circle(string name)
: base(name)
{ }
// 重寫父類抽像方法
public override void Draw()
{
Console.WriteLine("畫圓:" + Name);
}
public override void Add(Graphics g)
{
throw new Exception("不能向簡單圖形Circle添加其他圖形");
}
public override void Remove(Graphics g)
{
throw new Exception("不能向簡單圖形Circle移除其他圖形");
}
}
/// <summary>
/// 複雜圖形,由一些簡單圖形組成,假設該複雜圖形由兩條線組成
/// </summary>
public class ComplexGraphics : Graphics
{
private List<Graphics> complexGraphicsList = new List<Graphics>();
public ComplexGraphics(string name)
: base(name)
{ }
/// <summary>
/// 複雜圖形的畫法
/// </summary>
public override void Draw()
{
foreach (Graphics g in complexGraphicsList)
{
g.Draw();
}
}
public override void Add(Graphics g)
{
complexGraphicsList.Add(g);
}
public override void Remove(Graphics g)
{
complexGraphicsList.Remove(g);
}
}
class MyClass
{
static void Main(string[] args)
{
ComplexGraphics complexGraphics = new ComplexGraphics("複雜圖形 - 兩條線段組成的複雜圖形");
complexGraphics.Add(new Line("線段A"));
complexGraphics.Add(new Line("線段C"));
// 顯示複雜圖形的畫法
Console.WriteLine("複雜圖形的繪製:");
Console.WriteLine("---------------------");
complexGraphics.Draw();
Console.WriteLine("複雜圖形繪製完成");
Console.WriteLine("---------------------");
}
}
參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD