本系列所有設計模式均為轉載,原文地址:http://www.cnblogs.com/zhenyulu/articles/36058.html
課本:《C#設計模式》,電子工業出版社,ISBN 7-5053-8979-3。33元含光碟片。
課程內容:設計模式
來源:亞曆山大的建築模式、Gamma等人(1995)創作的"Design Patterns: Elements of Reusable Software"。這本書通常被稱作"Gang of Four"或"GoF",開創性的創造了《設計模式》。
也有人說"三十六計"就是"模式"。
一、 C# 物件導向程式設計複習
點擊http://files.cnblogs.com/zhenyulu/CSharp.rar下載,內容包括:
欄位與屬性.cs
屬性、方法作用範圍.cs
一加到一百.cs
使用介面排序(2).cs
使用介面排序(1).cs
求質數.cs
冒泡法排序.cs
九九表.cs
靜態與非靜態.cs
建構函式.cs
方法重載.cs
多態性.cs
遞迴求階乘.cs
列印三角形.cs
傳值調用與引用調用.cs
二、 設計模式舉例
在設計模式中有一種模式叫Builder模式,其原理如下:
我們可以將Builder理解成電飯鍋,給這個Builder放進去米和水,經過Builder的Build後,我們就可以取出香噴噴的米飯了。
C#中有一個類叫StringBuilder,輸入必要的資訊後,就可以取出對應的String。其使用方法如下:
using System;
using System.Text;
class Exam
{
public static void Main()
{
StringBuilder sb = new StringBuilder();
sb.Append('a',2);
sb.Append('b',3);
sb.Append('c',4);
Console.WriteLine(sb.ToString()); //列印出 aabbbcccc
sb.Remove(0, sb.Length); //清除sb中的所有資訊
}
}
程式執行結果為: aabbbcccc
請使用StringBuilder對以下列印三角型的程式進行改寫,寫出新程式。
using System;
public class Exam
{
public static void Main()
{
Console.Write("請輸入行數:");
int lines = int.Parse(Console.ReadLine());
Console.WriteLine("");
for(int i=1; i<=lines ; i++)
{
for(int k=1; k<= lines-i; k++)
Console.Write(" ");
for(int j=1; j<=i*2-1; j++)
Console.Write("*");
Console.WriteLine("");
}
}
}
答:
using System;
using System.Text;
class Exam
{
public static void Main()
{
Console.Write("請輸入行數:");
int lines = int.Parse(Console.ReadLine());
Console.WriteLine("");
StringBuilder sb = new StringBuilder();
for(int i=1; i<=lines ; i++)
{
sb.Append(' ', lines-i);
sb.Append('*', i*2-1);
Console.WriteLine(sb.ToString());
sb.Remove(0, sb.Length);
}
}
} 三、 先有雞還是先有蛋?
到底是先有雞還是先有蛋?看下面的代碼:
using System;
class Client
{
public static void Main ()
{
Base b = new Base();
Derived d = new Derived();
b.d = d;
Console.WriteLine(b.d.m);
}
}
class Base
{
public int n = 9;
public Derived d;
}
class Derived : Base
{
public int m = 10;
}
Derived繼承自Base,可以說沒有Base就沒有Derived,可Base裡面有一個成員是Derived類型。到底是先有雞還是先有蛋?這個程式可以正常編譯執行並列印結果10。
四、 大瓶子套小瓶子還是小瓶子套大瓶子?
另外一個例子:
using System;
class Client
{
public static void Main ()
{
A a = new A();
B b = new B();
a.b = b;
b.a = a;
}
}
class A
{
public B b;
}
class B
{
public A a;
}
上面的代碼似乎描述了"a包含b,b包含a"的關係,到底是大瓶子套小瓶子還是小瓶子套大瓶子呢?
五、 .net本質
關於"先有雞還是先有蛋"的程式,系統運行後,記憶體結構如下:
由圖中可以看出,根本不存在雞與蛋的問題,而是型與值的問題以及指標引用的問題。
關於"大瓶子套小瓶子還是小瓶子套大瓶子"問題,系統運行後,記憶體結構如下:
由於是指標引用,所以也無所謂大瓶子還是小瓶子了。
關於更多內容可以參考《.NET本質論 第1卷:公用語言運行庫》。
參考文獻:
閻宏,《Java與模式》,電子工業出版社
[美]James W. Cooper,《C#設計模式》,電子工業出版社
[美]Alan Shalloway James R. Trott,《Design Patterns Explained》,中國電力出版社
[美]Robert C. Martin,《敏捷式軟體開發 (Agile Software Development)-原則、模式與實踐》,清華大學出版社
[美]Don Box, Chris Sells,《.NET本質論 第1卷:公用語言運行庫》,中國電力出版社
http://www.dofactory.com/Patterns/Patterns.aspx