2012年4月18日? 天氣陰?? 天氣灰蒙蒙的,對于我們這種要為畢業做準備的人來說,這天氣舒服,涼爽?? 中午睡了一個時后? 打開電腦? 突然感覺? 眼睛不適應電腦屏幕的亮度,就是最近眼睛看電腦太久了?? 不工作 了?? 呵呵?? 看來該休息一下嘍????? 好久沒更新文章了??? 更新一個吧
單例模式
using System;
using System.Collections.Generic;using System.Text;
using System.IO;
namespace 單例模式
{
??? //單例模式介紹
??? //一個類在一個程序中只有一個對象
??? //類似于程序的配置文件,一個程序中只能有一個配置文件,多個的話,程序 不知道在哪個文件去調
??? //應用?? 文件緩存管理器
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? //Earth ea=new Earth();//不能創建對象
??????????? /*Earth ea1=Earth.getEarth();
??????????? Earth ea2=Earth.getEarth();
??????????? Console.WriteLine(object.ReferenceEquals(ea1,ea2));//看是否是同一個對象?? return true;
??????????? */
??????????? //應用? 文件緩存器
??????????? FileCacheManager fc = FileCacheManager.instanse;//因為instanse是filecachemanager唯一的對象 ,所以其他類都只存這個對象的值
??????????? string s=fc.ReadFile(@"c:\1.txt");
??????????? Console.WriteLine(s);
??????????? System.Threading.Thread.Sleep(8000);//為看到效果? 在睡的8秒中? 把文本文件?? 修改一下? 看能否得到正確結果
??????????? s = fc.ReadFile(@"c:\1.txt");
??????????? Console.WriteLine(s);
??????????? Console.ReadKey();
??????? }
??? }
??? class Earth
??? {
??????? //static的賦值語句運行一次(在類的第一次加載的時候)
??????? private static Earth instanse = new Earth();//2、聲明一個靜態字段,初始化一個實例(提供對象的唯一實例)
??????? private Earth()//1、把構造函數private(防止外部調用構造函數創建對象)
??????? {
??????? }
??????? public static Earth getEarth()//3、編寫一個靜態方法或者靜態屬性,返回那個唯一的實例
??????? {
??????????? return instanse;
??????? }
??????? public int population { get; set; }
??? }
??? sealed class FileCacheManager//新建一個文件緩存管理器類? 防止繼承?? 用sealed關鍵字
??? {
??????? public static readonly FileCacheManager instanse = new FileCacheManager();//設置一個只讀的變量? 存儲該對象 ?
??????? Dictionary<string, CacheItem> dic = new Dictionary<string, CacheItem>();//創建字典
??????? private FileCacheManager()
??????? {
??????? }
??????? public string ReadFile(string filename)
??????? {
??????????? if (dic.ContainsKey(filename))//判斷文件 是否已讀
??????????? {
??????????????? DateTime lasttime = File.GetLastWriteTime(filename);
??????????????? if (lasttime == dic[filename].lastwriteTime)//判斷文件 是否修改?? 根據最后修改時間
??????????????? {
??????????????????? return dic[filename].content;
??????????????? }
??????????????? else
??????????????????? return readtext(filename);
??????????? }
??????????? else
??????????? {
??????????????? return readtext(filename);
??????????? }
??????? }
??????? private string readtext(string filename)//讀取文件? 放到字典中
??????? {
??????????? string txt = File.ReadAllText(filename);
??????????? CacheItem ch = new CacheItem();
??????????? ch.content = txt;
??????????? ch.lastwriteTime = File.GetLastWriteTime(filename);//因為文件有可能被修改? 為了獲取的數據保持同步 所以保存他的最后修改時間? 再去判斷一下
??????????? dic[filename] = ch;//寫入字典
??????????? return txt;
??????? }
??? }
??? class CacheItem//用于保存緩存項
??? {
??????? public string content;
??????? public DateTime lastwriteTime;
??? }
}