项目中用到的设计模式(持续更新)
設(shè)計模式的定義:是指在軟件開發(fā)中,經(jīng)過驗(yàn)證的,用于解決在特定環(huán)境下,重復(fù)出現(xiàn)的,特定問題的解決方案。
設(shè)計的六大原則:
?單一職責(zé)原則(Single Responsibility Principle, SRP):一個類只負(fù)責(zé)一個功能領(lǐng)域中的相應(yīng)職責(zé),或者可以定義為:就一個類而言,應(yīng)該只有一個引起它變化的原因。
?開閉原則(Open-Closed Principle, OCP):一個軟件實(shí)體應(yīng)當(dāng)對擴(kuò)展開放,對修改關(guān)閉。即軟件實(shí)體應(yīng)盡量在不修改原有代碼的情況下進(jìn)行擴(kuò)展。
?里氏代換原則(Liskov Substitution Principle, LSP):所有引用基類(父類)的地方必須能透明地使用其子類的對象。
?依賴倒轉(zhuǎn)原則(Dependency Inversion? Principle, DIP):抽象不應(yīng)該依賴于細(xì)節(jié),細(xì)節(jié)應(yīng)當(dāng)依賴于抽象。換言之,要針對接口編程,而不是針對實(shí)現(xiàn)編程。
?接口隔離原則(Interface? Segregation Principle, ISP):使用多個專門的接口,而不使用單一的總接口,即客戶端不應(yīng)該依賴那些它不需要的接口。
?迪米特法則(Law of? Demeter, LoD):一個軟件實(shí)體應(yīng)當(dāng)盡可能少地與其他實(shí)體發(fā)生相互作用。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
接口和抽象類的選擇:
1.優(yōu)先使用接口
2.在既要定義子類的行為,又要為子類提供公共的功能時應(yīng)選擇抽象類。
-------------------------------------------------------創(chuàng)建類模式------------------------------------------------------
0.簡單工廠模式(靜態(tài)工廠)(本質(zhì):選擇實(shí)現(xiàn))
public sealed class ContractCardRulesFactory {public static IContractRules CreateContractRules(){return new ContractRules()} } public interface IContractRules{DataTable GetContractsWithRecAndPay(Dictionary<string, object> filter); } public class ContractRules : IContractRules{ }
客戶端:
DataTable dt = ContractCardRulesFactory.CreateContractRules().GetContractsWithRecAndPay(filter);StructureMap:
IList<T_HZ_MDT> t_HZ_MDTList = ObjectFactory.GetInstance<IDAL_T_HZ_MDT>().GetList(mDTQueryParams);1.單例模式(本質(zhì):控制實(shí)例數(shù)目)
public class Message implements Serializable{/*** 消息表*/private static final long serialVersionUID = -3133864495085075021L;private Message(){}private static final Message message = new Message();public static Message getInstance(){return message;}private int ID;private int VERIFY_TAG;private int VERIFY_TYPE;private String VERIFY_SBBH;private int DR;private int CODE;private String COLLECTOR_ID;public void setID(int iD) {ID = iD;}public int getID() {return ID;}public void setVERIFY_TAG(int vERIFY_TAG) {VERIFY_TAG = vERIFY_TAG;}public int getVERIFY_TAG() {return VERIFY_TAG;}public void setVERIFY_TYPE(int vERIFY_TYPE) {VERIFY_TYPE = vERIFY_TYPE;}public int getVERIFY_TYPE() {return VERIFY_TYPE;}public void setVERIFY_SBBH(String vERIFY_SBBH) {VERIFY_SBBH = vERIFY_SBBH;}public String getVERIFY_SBBH() {return VERIFY_SBBH;}public void setDR(int dR) {DR = dR;}public int getDR() {return DR;}public void setCODE(int cODE) {CODE = cODE;}public int getCODE() {return CODE;}public void setCOLLECTOR_ID(String cOLLECTOR_ID) {COLLECTOR_ID = cOLLECTOR_ID;}public String getCOLLECTOR_ID() {return COLLECTOR_ID;} }
客戶端:
Message.getInstance().setVERIFY_TAG(3); Message.getInstance().setVERIFY_TYPE(1); Message.getInstance().setVERIFY_SBBH(ID); Message.getInstance().setCODE(code); Message.getInstance().setCOLLECTOR_ID(ID); insertMessageService.insertMessage();//插入消息表 public void insertMessage(){Map<String,Object> param = new HashMap<String,Object>();param.put("ID", getMaxMessageID());param.put("verify_tag", Message.getInstance().getVERIFY_TAG());//變動類型標(biāo)識,新增為1修改為2刪除為3param.put("verify_type", Message.getInstance().getVERIFY_TYPE());//1是采集設(shè)備 2是熱表param.put("verify_sbbh", Message.getInstance().getVERIFY_SBBH());//采集點(diǎn)編號param.put("dr", 0);//默認(rèn)為0 未同步param.put("code", Message.getInstance().getCODE());//廠家編號param.put("collector_id", Message.getInstance().getCOLLECTOR_ID());//集中器編號fileMaintenanceMapper.insertMessage(param);}2.工廠方法模式(延遲到子類來選擇實(shí)現(xiàn))與IOC
抽象工廠類,具體工廠類,去掉抽象工廠類,變成簡單工廠或者靜態(tài)工廠模式
3.抽象工廠模式(本質(zhì),選擇產(chǎn)品簇的實(shí)現(xiàn) )與DAO模式
工廠方法是單個產(chǎn)品的實(shí)現(xiàn)
多個產(chǎn)品,多個工廠?DbProviderFactory
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); //獲取工廠 這句就可以獲得一個工廠,用這個工廠就可發(fā)生產(chǎn)該數(shù)據(jù)提供程序的各種對象了。 如果是連接 SqlServer:DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); Oracle:DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient"); ODBC:DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.Odbc");4.建造者模式(本質(zhì):分離整體構(gòu)建算法和部件構(gòu)造)
.NET環(huán)境下的字符串處理StringBuilder,這是一種簡化了的建造者模式
5.原型模式(本質(zhì):克隆生成對象)
通過克隆來創(chuàng)建新的對象實(shí)例
為克隆出來的新的對象實(shí)例復(fù)制原型實(shí)例屬性的值
public Object Clone(){return (Object)this.MemberwiseClone();}實(shí)現(xiàn)克隆操作,在.NET中可以使用Object類的MemberwiseClone()方法來實(shí)現(xiàn)對象的淺表拷貝或通過序列化的方式來實(shí)現(xiàn)深拷貝。
------------------------------------------------------行為類模式-------------------------------------------------------
6.迭代器模式(本質(zhì):控制訪問聚合對象中的元素)
能用foreach遍歷訪問的對象必須是集合或數(shù)組對象,而這些都是靠實(shí)現(xiàn)超級接口IEnumerator或被聲明 GetEnumerator 方法的類型
7.命令模式(封裝請求)
(封裝請求)事務(wù),Transaction
例子:
//抽象命令public abstract class Command{protected Barbecuer receiver;public Command(Barbecuer receiver){this.receiver = receiver;}//執(zhí)行命令abstract public void ExcuteCommand();} //烤羊肉串命令class BakeMuttonCommand : Command{public BakeMuttonCommand(Barbecuer receiver): base(receiver){ }public override void ExcuteCommand(){receiver.BakeMutton();}}//烤雞翅命令class BakeChickenWingCommand : Command{public BakeChickenWingCommand(Barbecuer receiver): base(receiver){ }public override void ExcuteCommand(){receiver.BakeChickenWing();}} //烤肉串者Receiverpublic class Barbecuer{public void BakeMutton(){Console.WriteLine("烤羊肉串!");}public void BakeChickenWing(){Console.WriteLine("烤雞翅!");}} //服務(wù)員Invokerpublic class Waiter{private IList<Command> orders = new List<Command>();//設(shè)置訂單public void SetOrder(Command command){if (command.ToString() == "命令模式.BakeChickenWingCommand"){Console.WriteLine("服務(wù)員:雞翅沒有了,請點(diǎn)別的燒烤。");}else{orders.Add(command);Console.WriteLine("增加訂單:" + command.ToString() + " 時間:" + DateTime.Now.ToString());}}//取消訂單public void CancelOrder(Command command){orders.Remove(command);Console.WriteLine("取消訂單:" + command.ToString() + " 時間:" + DateTime.Now.ToString());}//通知全部執(zhí)行public void Notify(){foreach (Command cmd in orders){cmd.ExcuteCommand();}}} static void Main(string[] args){//開店前的準(zhǔn)備 客戶端Barbecuer boy = new Barbecuer();Command bakeMuttonCommand1 = new BakeMuttonCommand(boy);Command bakeMuttonCommand2 = new BakeMuttonCommand(boy);Command bakeChickenWingCommand1 = new BakeChickenWingCommand(boy);Waiter girl = new Waiter();//開門營業(yè) 顧客點(diǎn)菜 girl.SetOrder(bakeMuttonCommand1);girl.SetOrder(bakeMuttonCommand2);girl.SetOrder(bakeChickenWingCommand1);//點(diǎn)菜完閉,通知廚房 girl.Notify();Console.Read();}8.解釋器模式(本質(zhì):分離實(shí)現(xiàn),解釋執(zhí)行)
9.職責(zé)鏈模式(分離職責(zé),動態(tài)組合)
10.觀察者模式(本質(zhì):觸發(fā)聯(lián)動)
net事件
11.中介者模式(本質(zhì):封裝交互)
private System.Windows.Forms.ComboBox comboBox1;private System.Windows.Forms.ComboBox comboBox2;private void InitializeComponent(){// // comboBox1// this.comboBox1.FormattingEnabled = true;this.comboBox1.Location = new System.Drawing.Point(51, 25);this.comboBox1.Name = "comboBox1";this.comboBox1.Size = new System.Drawing.Size(113, 20);this.comboBox1.TabIndex = 0;// // comboBox2// this.comboBox2.FormattingEnabled = true;this.comboBox2.Location = new System.Drawing.Point(245, 25);this.comboBox2.Name = "comboBox2";this.comboBox2.Size = new System.Drawing.Size(109, 20);this.comboBox2.TabIndex = 1;
Windows 窗體設(shè)計器
//國家 colleagueabstract class Country{protected UnitedNations mediator;public Country(UnitedNations mediator){this.mediator = mediator;}} //美國 concretecolleagueclass USA : Country{public USA(UnitedNations mediator): base(mediator){}//聲明public void Declare(string message){mediator.Declare(message, this);}//獲得消息public void GetMessage(string message){Console.WriteLine("美國獲得對方信息:" + message);}}//伊拉克concretecolleagueclass Iraq : Country{public Iraq(UnitedNations mediator): base(mediator){}//聲明public void Declare(string message){mediator.Declare(message, this);}//獲得消息public void GetMessage(string message){Console.WriteLine("伊拉克獲得對方信息:" + message);}} //聯(lián)合國機(jī)構(gòu) mediatorabstract class UnitedNations{/// <summary>/// 聲明/// </summary>/// <param name="message">聲明信息</param>/// <param name="colleague">聲明國家</param>public abstract void Declare(string message, Country colleague);} //聯(lián)合國安全理事會 concretemediatorclass UnitedNationsSecurityCouncil : UnitedNations{private USA colleague1;private Iraq colleague2;public USA Colleague1{set { colleague1 = value; }}public Iraq Colleague2{set { colleague2 = value; }}public override void Declare(string message, Country colleague){if (colleague == colleague1){colleague2.GetMessage(message);}else{colleague1.GetMessage(message);}}}12.備忘錄模式(本質(zhì):保存和回恢復(fù)內(nèi)部狀態(tài))
(保存和恢復(fù)內(nèi)部狀態(tài))
13.狀態(tài)模式(工作流,本質(zhì):根據(jù)狀態(tài)來分離和選擇行為)
14.策略模式(本質(zhì):分離算法,選擇實(shí)現(xiàn))
public interface IAddFileMaintenance {public abstract String AddFileMaintenance(); } public class CreateHeatCompany implements IAddFileMaintenance{private StringBuilder getheatCompanyList;private StringBuilder getProvinceList;private StringBuilder getcityList;public CreateHeatCompany(StringBuilder getheatCompanyList,StringBuilder getProvinceList,StringBuilder getcityList){this.getheatCompanyList = getheatCompanyList;this.getProvinceList = getProvinceList;this.getcityList = getcityList;}public String AddFileMaintenance() {String result = "";StringBuilder sb = new StringBuilder();sb.append("<table id = 'table_1' width='99%' border='0' cellspacing='0' cellpadding='0'>");sb.append("<tr><th width='31%' class='boldth'>熱力公司檔案</th><td width='69%'> </td></tr>");sb.append("<tr><th>熱力公司名稱:</th><td><input type='text' class='inputbg_td' id='name' maxlength='20' /></td></tr>");sb.append("<tr><th>熱力公司編號:</th><td><input type='text' class='inputbg_td' id='corp_id' maxlength='12'/></td></tr>");sb.append("<tr><th>上級熱力公司:</th><td><select id='select1' class='selectbg_td'>");sb.append("<option value='0'></option>");sb.append(this.getheatCompanyList);sb.append("</select></td></tr>");sb.append("<tr><th>熱力公司地址:</th><td><input type='text' class='inputbg_td' id='address' maxlength='30'/></td></tr>");sb.append("<tr><th>地理位置:</th><td><input type='text' class='inputbg_td' id='geo_address' maxlength='30'/></td></tr>");sb.append("<tr><th height='73'>所屬地區(qū):</th><td><select id='select2' class='selectbg_tdd' οnchange='change(this)'>");sb.append(this.getProvinceList);sb.append("</select>省<select id='select3' class='selectbg_tdd'>"); sb.append(this.getcityList);sb.append("</select>市</td></tr>");sb.append("<tr><th>供熱面積:</th><td><input type='text' class='inputbg_td' id='area' maxlength='15' onKeypress='isNumber();'/></td></tr>"); sb.append("<tr><td> </td><td align='right'>");sb.append("<a οnclick='cancel();'><img src='images/hou_btn_11.gif' width='76' height='25' /></a>");sb.append("<a οnclick='save(1);'><img src='images/hou_btn_03.jpg' width='76' height='25' /></a></td></tr>");sb.append("</table>");result = sb.toString();result = result.replace("'", "\"");return result;}} public class AddFileMaintenanceContext {private IAddFileMaintenance iAddFileMaintenance;public AddFileMaintenanceContext(IAddFileMaintenance iAddFileMaintenance){this.iAddFileMaintenance = iAddFileMaintenance;}public String AddFileMaintenance(){return this.iAddFileMaintenance.AddFileMaintenance();} }
客戶端:
private AddFileMaintenanceContext createHeatCompanyContext() {return new AddFileMaintenanceContext(new CreateHeatCompany(getheatCompanyList(),getProvinceList(this.province),getcityList(this.beiJingCity)));}
15.模板方法模式(本質(zhì):固定算法骨架)
被繼承的抽象類
16.訪問者模式(本質(zhì):預(yù)留通路,回調(diào)實(shí)現(xiàn))
------------------------------------------------------結(jié)構(gòu)類模式-------------------------------------------------------
17.適配器模式(本質(zhì),轉(zhuǎn)換匹配,復(fù)用功能)
復(fù)用已有的功能,不是實(shí)現(xiàn)新的接口
對象適配器:
類適配器:
public interface ICacheStorage{void Remove(string key);void Store(string key, object data);T Retrieve<T>(string storageKey);} public class HttpContextCache : ICacheStorage{public void Remove(string key){HttpContext.Current.Cache.Remove(key);}public void Store(string key, object data){HttpContext.Current.Cache.Insert(key, data);}public T Retrieve<T>(string key){T itemStored = (T)HttpContext.Current.Cache.Get(key);if (itemStored == null)itemStored = default(T);return itemStored;}}這里適配的是 :?HttpContext
客戶端:
ICacheStorage cache = new HttpContextCache();cache.Store("useid", cookie["userid"].ToString());18.組合模式(本質(zhì)是統(tǒng)一葉子對象和組合對象)
具有整體與部分的關(guān)系,并能組合成樹型結(jié)構(gòu)的對象結(jié)構(gòu)
19.代理模式(本質(zhì):控制對象的訪問)
和適配器模式的區(qū)別:
public I6.CM.ContractCard.Entity.ContractEntity.EContractStatus GetContractStatus(string conSystemCode) {KernelProxyClient client = new KernelProxyClient();object[] result = client.Invoke("I6.CM.ContractCard.Facade.ContractFacade.GetContractStatus", new object[] {conSystemCode}, new int[] {0});return ((I6.CM.ContractCard.Entity.ContractEntity.EContractStatus)(result[0]));}
20.橋梁模式(分離抽象與實(shí)現(xiàn))
抽象部分和實(shí)現(xiàn)部分分離,可以獨(dú)立的變化,二個緯度以上變化的時候
java中的JDBC
21.裝飾模式(本質(zhì):動態(tài)組合)
動態(tài)的生成子類
DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream("IOTest.txt") ) );
AOP:
22.門面模式(外觀模式Facade,本質(zhì):封裝交互,簡化調(diào)用)
public bool Update(ref ContractEntity entity,string rightDataType){try{i6DbHelper.Open();IDataRightRules editDataRightRules = DataCatalogRulesFactory.CreateDataRightRules(rightDataType + "_edit");DataRightsForUserEntity editDataRights = GetAllRightForUser(editDataRightRules, entity, AppSessionConfig.LoginID,AppSessionConfig.OCode);IDataRightRules viewDataRightRules = DataCatalogRulesFactory.CreateDataRightRules(rightDataType + "_view");DataRightsForUserEntity viewDataRights = GetAllRightForUser(viewDataRightRules, entity, AppSessionConfig.LoginID, AppSessionConfig.OCode);i6DbHelper.BeginTran();ContractCardRulesFactory.CreateContractRules().Update(entity);i6DbHelper.CommitTran();return true;}catch (Exception e){i6DbHelper.RollbackTran();throw e;}finally{i6DbHelper.Close();}}
體現(xiàn)了最少知識原則
23.享元模式(本質(zhì):分離與共享)
//緩存菜單String result = "";if(request.getSession().getAttribute(operatorID + location) == null){Map<String,Object> param = new HashMap<String,Object>();param.put("operatorID", operatorID);param.put("location", location);List<Tree> treeList = loginService.getMenusByID(param);RightsManagementControllerHelp help = new RightsManagementControllerHelp(); help.setTreeList(treeList);if(location == SystemType.FrontSystem.value()){result = help.getFrontHtml();systemLogService.saveSystemLog(operatorID, "登錄到前臺界面");}else{result = help.getBackHtml();systemLogService.saveSystemLog(operatorID, "登錄到后臺界面");} request.getSession().setAttribute(operatorID + location, result); }else{result = request.getSession().getAttribute(operatorID + location).toString();} return result;
做一個享元工廠緩存菜單
(分離與共享)
//網(wǎng)站 flyweightabstract class WebSite{public abstract void Use(User user);} //具體的網(wǎng)站 concreteflyweightclass ConcreteWebSite : WebSite{private string name = "";public ConcreteWebSite(string name){this.name = name;}public override void Use(User user){Console.WriteLine("網(wǎng)站分類:" + name + " 用戶:" + user.Name);}} //網(wǎng)站工廠flyweightfactoryclass WebSiteFactory{private Hashtable flyweights = new Hashtable();//獲得網(wǎng)站分類public WebSite GetWebSiteCategory(string key){if (!flyweights.ContainsKey(key))flyweights.Add(key, new ConcreteWebSite(key));return ((WebSite)flyweights[key]);}//獲得網(wǎng)站分類總數(shù)public int GetWebSiteCount(){return flyweights.Count;}}總結(jié)
以上是生活随笔為你收集整理的项目中用到的设计模式(持续更新)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Asp.net生成工作流、审批流的解决方
- 下一篇: 安装sql server 2008 报错