C#面向?qū)ο笤O(shè)計(jì)原則之開閉原則
開閉原則(OCP)
定義:對擴(kuò)展開發(fā),對修改關(guān)閉。
好處:
- 適應(yīng)性和靈活性。
- 穩(wěn)定性和延續(xù)性。
- 可復(fù)用性與可維護(hù)性。
解釋說明:開閉原則指的是兩方面:對功能擴(kuò)展開發(fā),對修改進(jìn)行關(guān)閉;有時(shí)當(dāng)用戶要求或需求發(fā)生變化時(shí),我們不得不打開原來的代碼進(jìn)行修改,進(jìn)行功能的擴(kuò)展或增加,這種設(shè)計(jì)如果應(yīng)用到我們以后的項(xiàng)目開發(fā)中會導(dǎo)致嚴(yán)重的問題,這樣容易導(dǎo)致意外的錯(cuò)誤。好的程序,應(yīng)該保證在我們進(jìn)行程序擴(kuò)展時(shí),不會更改以前的代碼。如何才能保證這樣的效果呢?我們在定義一個(gè)類的功能時(shí):最好先定義他的抽象類或接口,這樣在功能擴(kuò)展時(shí),我們只需要在原來抽象類和接口的基礎(chǔ)上編寫新的實(shí)現(xiàn)類和子類,這樣既能擴(kuò)展功能又不影響以前的功能。
示例:
定義數(shù)據(jù)庫鏈接的接口
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 開閉原則_OCP_
{
/// <summary>
/// 數(shù)據(jù)庫連接
/// </summary>
public interface IDbConnection
{
public DbConnection GetConnection();
}
}分別定義兩個(gè)接口的實(shí)現(xiàn)類
SQL Server數(shù)據(jù)庫實(shí)現(xiàn)類:
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace 開閉原則_OCP_
{
public class SqlServerDbConnection :IDbConnection
{
public DbConnection GetConnection()
{
// 連接數(shù)據(jù)庫并返回
return new SqlConnection();
}
}
}Oracle數(shù)據(jù)庫實(shí)現(xiàn)類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OracleClient;
using System.Data.Common;
using System.Data.OracleClient;
namespace 開閉原則_OCP_
{
public class OracleDbConnection:IDbConnection
{
public DbConnection GetConnection()
{
// 連接數(shù)據(jù)庫并返回
return new OracleConnection();
}
}
}如果又增加了一個(gè)數(shù)據(jù)庫,只需要在定義一個(gè)接口的實(shí)現(xiàn)類就可以。接口不會發(fā)生變化,接口的實(shí)現(xiàn)類實(shí)現(xiàn)了多樣性,這樣就實(shí)現(xiàn)了開閉原則。
代碼下載鏈接:點(diǎn)此下載
到此這篇關(guān)于C#面向?qū)ο笤O(shè)計(jì)原則之開閉原則的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#實(shí)現(xiàn)六大設(shè)計(jì)原則之依賴倒置原則
- C#面向?qū)ο笤O(shè)計(jì)原則之組合/聚合復(fù)用原則
- C#面向?qū)ο笤O(shè)計(jì)原則之接口隔離原則
- C#面向?qū)ο笤O(shè)計(jì)原則之里氏替換原則
- C#面向?qū)ο笤O(shè)計(jì)原則之單一職責(zé)原則
- C#實(shí)現(xiàn)六大設(shè)計(jì)原則之迪米特法則
- C#實(shí)現(xiàn)六大設(shè)計(jì)原則之接口隔離原則
- C#實(shí)現(xiàn)六大設(shè)計(jì)原則之里氏替換原則
- C#實(shí)現(xiàn)六大設(shè)計(jì)原則之單一職責(zé)原則
- 淺談C#六大設(shè)計(jì)原則
- C#編程之依賴倒置原則DIP
相關(guān)文章
C#多線程之Thread中Thread.Join()函數(shù)用法分析
這篇文章主要介紹了C#多線程之Thread中Thread.Join()函數(shù)用法,實(shí)例分析了Thread.Join()方法的原理與使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
C#調(diào)用OpenCV開發(fā)簡易版美圖工具【推薦】
本文主要介紹在WPF項(xiàng)目中使用OpenCVSharp3-AnyCPU開源類庫處理圖片,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-10-10
C#實(shí)現(xiàn)判斷字符串中是否包含中文的方法
這篇文章主要介紹了C#實(shí)現(xiàn)判斷字符串中是否包含中文的方法,非常實(shí)用的功能,需要的朋友可以參考下2014-08-08
C#結(jié)合數(shù)據(jù)庫實(shí)現(xiàn)驗(yàn)證識別ID卡內(nèi)容的方法
這篇文章主要介紹了C#結(jié)合數(shù)據(jù)庫實(shí)現(xiàn)驗(yàn)證識別ID卡內(nèi)容的方法,非常實(shí)用的功能,需要的朋友可以參考下2014-07-07

