C#項目中常用到的設計模式

C#項目中常用到的設計模式

1. 引言

一個項目的通常都是從Demo開始,不斷為項目添加新的功能以及重構,也許剛開始的時候代碼顯得非常凌亂,毫無設計可言。但是隨著項目的迭代,往往需要將很多相同功能的代碼抽取出來,這也是設計模式的開始。熟練運用設計模式應該是每一個軟件開發人員的必備技能。今天給大家介紹幾個常用的設計模式。

?

2. 單例模式

單例模式恐怕是很多開發人員最先接觸到的模式之一,可以認為就是一個全局變量。它的初始化過程無非就是一開始就new 一個instance,或者惰性初始化等需要用到的時候new 一個instance。這里需要注意的是在多線程情況下new一個instance。通常加上lock 可以解決問題。這里我們利用C# 的系統函數 Interlocked.CompareExchange

    internal class SingletonOne{private static SingletonOne _singleton;private SingletonOne(){}public static SingletonOne Instance{get{if (_singleton == null){Interlocked.CompareExchange(ref _singleton, new SingletonOne(), null);}return _singleton;}}}

?

3. 迭代器模式

迭代器模式也是用的比較多的一種,通常見于C#的內置容器數據結構 List,Stack等等,為了便于遍歷容器內元素。這里給出一個簡單版的Stack實現

    internal class Stack<T> : IEnumerable<T>, IEnumerable{private T[] _array;private int _index;private const int DefaultSize = 4;public Stack(int size){var sized = size > 0 ? size : DefaultSize;this._array = new T[sized];this._index = 0;}public int Count{get { return this._index; }}public Stack(IEnumerable<T> data) : this(0){var enumrator = data.GetEnumerator();while (enumrator.MoveNext()){var item = enumrator.Current;this.Push(item);}}public void Push(T item){if (this._index < this._array.Length){this._array[this._index++] = item;}else{var newLength = this._array.Length << 1;T[] newArray = new T[newLength];Array.Copy(this._array, newArray, this.Count);this._array = newArray;this.Push(item);}}public T Pop(){if (this.Count <= 0){throw new ArgumentOutOfRangeException("pop");}else{this._array[this._index] = default(T);return this._array[--this._index];}}public T Get(int index){if (this.Count <= index){throw new ArgumentOutOfRangeException("Get");}else{return this._array[index];}}IEnumerator IEnumerable.GetEnumerator(){return this.GetEnumerator();}public IEnumerator<T> GetEnumerator(){return new StackEnumerator<T>(this);}}

Stack 的 迭代器內部實現:

    internal class StackEnumerator<T> : IEnumerator<T> , IEnumerator{private Stack<T> _stack;private int _index;public StackEnumerator(Stack<T> stack){this._stack = stack;this._index = -1;}public bool MoveNext(){this._index++;return this._index < this._stack.Count;}public void Reset(){this._index = -1;}object  IEnumerator.Current {get { return this.Current; } }public T Current{get { return this._stack.Get(this._index); }}public void Dispose(){this._stack = null;}}

?

4 工廠模式

工廠模式細分的話有簡單工廠模式、抽象工廠模式等。它最核心的就是如何通過 Factory new 一個 對象出來。在ASP.NET MVC 消息處理實現過程中工廠模式運用的非常多。比如

在MVC中處理一個Request,其實就是調用Controller下的一個Action,這就需要從Url 和Route 中反射出Controller對象,內部由ControllerFactory創建。

image

它的默認實現是:DefaultControllerFactory

image

另一個例子是ValueProviderFactory,它使得Controller 下的Action 能夠接收到前端傳回來的數據并實現模型綁定,是典型的抽象工廠實現。

image

?

5. 訂閱模式

訂閱模式在某些項目運用比較多,比如 Knockout 整個項目就是一個大的訂閱模式的實現,但是它是用javascript編寫的。還有像微博、微信公眾號等等訂閱模式通常少不了。

通常可以定義接口:

    internal interface ISubject{IEnumerable<IObserver> Observers { get; } void Notify();void AddObserver(IObserver observer);void RemoveObserver(IObserver observer);}internal interface IObserver{void ReceiveSubject(ISubject subject);}

實現:

    internal class AritcleObserver : IObserver{public void ReceiveSubject(ISubject subject){// receive the subject
        }}class WeChatArticle : ISubject{private ICollection<IObserver> _observers;private string _name;public WeChatArticle(string name){this._name = name;this._observers = new List<IObserver>();}public IEnumerable<IObserver> Observers{get { return this._observers; }}public void Notify(){foreach (IObserver observer in this._observers){observer.ReceiveSubject(this);}}public void AddObserver(IObserver observer){this._observers.Add(observer);}public void RemoveObserver(IObserver observer){this._observers.Remove(observer);}}

?

6.? 責任鏈模式

責任鏈模式沒有像工廠模式那樣被人熟悉,在ASP.NET WebApi 中有一個非常典型的實現 就是WebApi的消息處理管道HttpMessageHandler

image

這里給一個簡單的模擬

    class DataRequest{public string FileName { get; set; }}class DataResponse{public string Error { get; set; }public string Data { get; set; }}internal abstract class RequestHandler{public RequestHandler NextHandler { get; set; }public abstract DataResponse Process(DataRequest request);}class ReadRequestHandler : RequestHandler{public override DataResponse Process(DataRequest request){return new DataResponse(){Data = File.ReadAllText(request.FileName)};}}class ExistsRequestHandler : RequestHandler{public override DataResponse Process(DataRequest request){if (File.Exists(request.FileName)){return this.NextHandler.Process(request);}else{return new DataResponse(){Error = "no exists"};}}}

?

7. 組合模式

組合模式是使得單個對象和組合對象有一致的行為,一致的行為可以理解為擁有同一個接口,比如圖形顯示

    class ControlContext{}internal interface IControl{void Draw(ControlContext context);}class Line : IControl{public void Draw(ControlContext context){}}class Circle : IControl{public void Draw(ControlContext context){}}class CompositeControl : IControl{private List<IControl> controls;public CompositeControl(IList<IControl> cons){this.controls = new List<IControl>(cons);}public void Draw(ControlContext context){this.controls.ForEach(c => c.Draw(context));}public void Add(IControl control){this.controls.Add(control);}}

?

8. 總結

市場上有很多關于設計模式的書,但是基本的設計模式大概有20多種,本文給大家介紹了幾種項目中常見的設計模式,其實有些設計模式在實際項目已經不知不覺用起來了。

以后再給大家介紹其他的幾種設計模式。

?

歡迎訪問我的個人主頁 51zhang.net? 網站還在不斷開發中…..

posted on 2016-06-02 21:06?禪宗花園...迷失的佛 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/VectorZhang/p/5554388.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/257071.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/257071.shtml
英文地址,請注明出處:http://en.pswp.cn/news/257071.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

學習筆記(14):Python網絡編程并發編程-文件傳輸功能實現

立即學習:https://edu.csdn.net/course/play/24458/296245?utm_sourceblogtoedu 1.課程目的&#xff1a; 實現客戶端輸入下載文件的命令&#xff0c;然后將命令發送給服務端&#xff0c;服務端再執行下載文件的命令&#xff0c;最后將執行下載文件命令后的結果返回給客戶端&a…

NFS精簡版配置方法

此實驗的前提是防火墻需關閉。 1.關閉iptables /etc/init.d/iptables stop /etc/init.d/iptables status 2.關閉selinux setenforce 0 getenforce Permissive ---出現這個單詞即代表selinux臨時關閉&#xff0c;如需永久關閉則需修改/etc/sysconfig/selinux配置文件 …

Serializable接口中serialVersionUID字段的作用

序列化運行時使用一個稱為 serialVersionUID 的版本號與每個可序列化類相關聯&#xff0c;該序列號在反序列化過程中用于驗證序列化對象的發送者和接收者是否為該對象加載了與序列化兼容的類。 如果接收者加載的該對象的類的 serialVersionUID 與對應的發送者的類的版本號不同&…

重新認知指針

1、把指針指向的變量的數據類型稱為指針的數據類型&#xff1b;而任何一個指針變量本身數據值的類型都是unsigned long int 2.、指針變量名前的符號“*”表示的是指向運算。 3、不要認為“ *p" 是指針變量&#xff0c;指針變量是p而不是*p 4、

分布式數據庫 HBase

原文地址&#xff1a;http://www.oschina.net/p/hbase/ HBase 概念 HBase – Hadoop Database&#xff0c;是一個高可靠性、高性能、面向列、可伸縮的分布式存儲系統&#xff0c;利用HBase技術可在廉價PC Server上搭建起大規模結構化存儲集群。 HBase是Google Bigtable的開源實…

學習筆記(15):Python網絡編程并發編程-進程理論

立即學習:https://edu.csdn.net/course/play/24458/296423?utm_sourceblogtoedu 1.進程&#xff1a;正在運行的一個過程或者一個任務&#xff1b; 2.進程與程序的區別&#xff1a;程序是一堆代碼&#xff0c;程序運行起來就是進程了&#xff0c;一個程序運行兩次&#xff0c;算…

【翻譯】Designing Websites for iPhone X

讓網站適配 iphone X 英文原文地址&#xff1a;https://webkit.org/blog/7929/...本文原文地址&#xff1a;https://github.com/cnsnake11/... The section below about safe area insets was updated on Oct 31, 2017 to reflect changes in the iOS 11.2 beta. 以下關于safe …

指針作為函數參數引用數組的任意元素

void swap(int *a,int*b) {*a*a^*b;*b*a^*b;*a*a^*b; } swap(data[j],data[j1]&#xff09;; int data[10]{13,55,48,13,62,45,754,0,10};以上是我遇到的問題&#xff0c;我覺得調用這個swap函數是不能這樣直接把數組的某個元素直接丟給swap數據 在程序中參加數據處理的量不是指…

使用 Log4Net 記錄日志

第一步&#xff1a;下載Log4Net 下載地址&#xff1a;http://logging.apache.org/log4net/download_log4net.cgi 把下載的 log4net-1.2.11-bin-newkey解壓后&#xff0c;如下圖所示&#xff1a; 雙擊bin文件夾 雙擊net文件夾&#xff0c;選擇針對.NET FramerWork的不同版本 找…

Xcode常用快捷鍵

1. 文件CMD N: 新文件CMD SHIFT N: 新項目CMD O: 打開CMD S: 保存CMDOPtS&#xff1a;保存所有文件CMD SHIFT S: 另存為CMD W: 關閉窗口CMD Q :退出XcodeCMD SHIFT W: 關閉文件2. 編輯CMD [: 左縮進CMD ]: 右縮進CMDshiftF:項目中查找CMDG:查找下一個CMDshiftG:查…

學習筆記(16):Python網絡編程并發編程-開啟子進程的兩種方式

立即學習:https://edu.csdn.net/course/play/24458/296424?utm_sourceblogtoedu #方式一&#xff1a;使用python內置模塊multiprocessing下的process類 from multiprocessing import Process import time#定義進程函數 def task(name):print(%s is running&#xff01;%name)t…

ElasticSearch的API python調用

os json datetime datetime django.http HttpResponse reelasticsearch Elasticsearches Elasticsearch([])res8 es.search({:{:{:{::}}}} ) statistic():():hit res8[][]:a (%hit %hit[])a re.split(a);arow a:id row[] row[]idHttpResponse(a)轉載于:https://blog.51cto…

HDU 1757 A Simple Math Problem (矩陣快速冪)

題目鏈接&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid1757 在吳神的幫助下才明白如何構造矩陣&#xff0c;還是好弱啊。 此處盜一張圖 1 #include <iostream>2 #include <cstdio>3 #include <cstring>4 #include <cmath>5 #include <al…

Spring學習使用標簽來標記資源(@Component、@Repository、 @Service和@Controller)和用法(包括如何jsp正在使用)...

首先&#xff0c;在xml其中新增部分標有下劃線的文件&#xff0c;容器初始化的時候需要掃描包 注意&#xff1a; a. 包款掃描(下劃線部分)一定要加&#xff0c;默認是不掃描整個包。與每一包之間’&#xff0c;’開。如過具有同樣的父包&#xff0c;那么我們能夠用父包來取…

python 判斷字符串時是否是json格式方法

在實際工作中&#xff0c;有時候需要對判斷字符串是否為合法的json格式 解決方法使用json.loads,這樣更加符合‘Pythonic’寫法 代碼示例&#xff1a; Python import json def is_json(myjson):try:json_object json.loads(myjson)except ValueError, e:return Falsereturn Tr…

學習筆記(17):Python網絡編程并發編程-Process對象的其他屬性或方法

立即學習:https://edu.csdn.net/course/play/24458/296427?utm_sourceblogtoedu 1.pid與ppid&#xff1a;pid進程編碼&#xff0c;ppid進程的父進程編碼&#xff1b;os.getpid()查看正在運行的進程編碼&#xff0c;os.getppid()查看正在運行進程的父進程編碼 2.僵尸進程&…

用弦截法求一元三次方程的根x^3-5x^2+16x-80=0 ;帶注釋!

//用弦截法求一元三次方程的根x^3-5x^216x-800 #include<stdio.h>#include<math.h> float f(float x) //定義子函數f(x) x^3-5x^216x-80&#xff0c;當f(x) →0時&#xff0c;則x即為所求的實數根&#xff1b; { float y; y((x-5.0)*x16.0)*x-80.0; …

兩個很有用的進程間通信函數popen,pclose

兩個很有用的進程間通信函數popen,pclose 今天起的比較晚&#xff0c;然后來了也不想復習&#xff0c;還是看書學習--寫代碼--寫博客有意思&#xff0c;不敢說有多精通&#xff0c;至少每天都在學習新知識&#xff0c;不求立刻完全消化&#xff0c;但求每天有進步。 現在就看看…

c++中指針箭頭的用法

1、c中指針用箭頭來引用類或者結構體的成員&#xff0c;箭頭操作符“->”用來引用指針對象。這是是用于類&#xff0c;或者是結構體的指針變量用的。 如struct Point {int x,y;};Point *ptnew Point;pt->x1; 舉例子說明一下&#xff1a;比如&#xff0c;我有一個對象dark…