项目中用到的设计模式(持续更新)
设计模式的定义:是指在软件开发中,经过验证的,用于解决在特定环境下,重复出现的,特定问题的解决方案。
设计的六大原则:
单一职责原则(Single Responsibility Principle, SRP):一个类只负责一个功能领域中的相应职责,或者可以定义为:就一个类而言,应该只有一个引起它变化的原因。
开闭原则(Open-Closed Principle, OCP):一个软件实体应当对扩展开放,对修改关闭。即软件实体应尽量在不修改原有代码的情况下进行扩展。
里氏代换原则(Liskov Substitution Principle, LSP):所有引用基类(父类)的地方必须能透明地使用其子类的对象。
依赖倒转原则(Dependency Inversion Principle, DIP):抽象不应该依赖于细节,细节应当依赖于抽象。换言之,要针对接口编程,而不是针对实现编程。
接口隔离原则(Interface Segregation Principle, ISP):使用多个专门的接口,而不使用单一的总接口,即客户端不应该依赖那些它不需要的接口。
迪米特法则(Law of Demeter, LoD):一个软件实体应当尽可能少地与其他实体发生相互作用。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
接口和抽象类的选择:
1.优先使用接口
2.在既要定义子类的行为,又要为子类提供公共的功能时应选择抽象类。
-------------------------------------------------------创建类模式------------------------------------------------------
0.简单工厂模式(静态工厂)(本质:选择实现)
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.单例模式(本质:控制实例数目)
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());//变动类型标识,新增为1修改为2删除为3 param.put("verify_type", Message.getInstance().getVERIFY_TYPE());//1是采集设备 2是热表 param.put("verify_sbbh", Message.getInstance().getVERIFY_SBBH());//采集点编号 param.put("dr", 0);//默认为0 未同步 param.put("code", Message.getInstance().getCODE());//厂家编号 param.put("collector_id", Message.getInstance().getCOLLECTOR_ID());//集中器编号 fileMaintenanceMapper.insertMessage(param); }
2.工厂方法模式(延迟到子类来选择实现)与IOC
抽象工厂类,具体工厂类,去掉抽象工厂类,变成简单工厂或者静态工厂模式
3.抽象工厂模式(本质,选择产品簇的实现 )与DAO模式
工厂方法是单个产品的实现
多个产品,多个工厂 DbProviderFactory
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); //获取工厂 这句就可以获得一个工厂,用这个工厂就可发生产该数据提供程序的各种对象了。 如果是连接 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.建造者模式(本质:分离整体构建算法和部件构造)
.NET环境下的字符串处理StringBuilder,这是一种简化了的建造者模式
5.原型模式(本质:克隆生成对象)
通过克隆来创建新的对象实例
为克隆出来的新的对象实例复制原型实例属性的值
public Object Clone() { return (Object)this.MemberwiseClone(); }
实现克隆操作,在.NET中可以使用Object类的MemberwiseClone()方法来实现对象的浅表拷贝或通过序列化的方式来实现深拷贝。
------------------------------------------------------行为类模式-------------------------------------------------------
6.迭代器模式(本质:控制访问聚合对象中的元素)
能用foreach遍历访问的对象必须是集合或数组对象,而这些都是靠实现超级接口IEnumerator或被声明 GetEnumerator 方法的类型
7.命令模式(封装请求)
(封装请求)事务,Transaction
例子:
//抽象命令 public abstract class Command { protected Barbecuer receiver; public Command(Barbecuer receiver) { this.receiver = receiver; } //执行命令 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(); } }
//烤肉串者Receiver public class Barbecuer { public void BakeMutton() { Console.WriteLine("烤羊肉串!"); } public void BakeChickenWing() { Console.WriteLine("烤鸡翅!"); } }
//服务员Invoker public class Waiter { private IList<Command> orders = new List<Command>(); //设置订单 public void SetOrder(Command command) { if (command.ToString() == "命令模式.BakeChickenWingCommand") { Console.WriteLine("服务员:鸡翅没有了,请点别的烧烤。"); } 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()); } //通知全部执行 public void Notify() { foreach (Command cmd in orders) { cmd.ExcuteCommand(); } } }
static void Main(string[] args) { //开店前的准备 客户端 Barbecuer boy = new Barbecuer(); Command bakeMuttonCommand1 = new BakeMuttonCommand(boy); Command bakeMuttonCommand2 = new BakeMuttonCommand(boy); Command bakeChickenWingCommand1 = new BakeChickenWingCommand(boy); Waiter girl = new Waiter(); //开门营业 顾客点菜 girl.SetOrder(bakeMuttonCommand1); girl.SetOrder(bakeMuttonCommand2); girl.SetOrder(bakeChickenWingCommand1); //点菜完闭,通知厨房 girl.Notify(); Console.Read(); }
8.解释器模式(本质:分离实现,解释执行)
9.职责链模式(分离职责,动态组合)
10.观察者模式(本质:触发联动)
net事件
11.中介者模式(本质:封装交互)
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 窗体设计器
//国家 colleague abstract class Country { protected UnitedNations mediator; public Country(UnitedNations mediator) { this.mediator = mediator; } }
//美国 concretecolleague class 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); } } //伊拉克concretecolleague class 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); } }
//联合国机构 mediator abstract class UnitedNations { /// <summary> /// 声明 /// </summary> /// <param name="message">声明信息</param> /// <param name="colleague">声明国家</param> public abstract void Declare(string message, Country colleague); }
//联合国安全理事会 concretemediator class 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.备忘录模式(本质:保存和回恢复内部状态)
(保存和恢复内部状态)
13.状态模式(工作流,本质:根据状态来分离和选择行为)
14.策略模式(本质:分离算法,选择实现)
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'>所属地区:</th><td><select id='select2' class='selectbg_tdd' onchange='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 onclick='cancel();'><img src='images/hou_btn_11.gif' width='76' height='25' /></a>"); sb.append("<a onclick='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.模板方法模式(本质:固定算法骨架)
被继承的抽象类
16.访问者模式(本质:预留通路,回调实现)
------------------------------------------------------结构类模式-------------------------------------------------------
17.适配器模式(本质,转换匹配,复用功能)
复用已有的功能,不是实现新的接口
对象适配器:
类适配器:
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.组合模式(本质是统一叶子对象和组合对象)
具有整体与部分的关系,并能组合成树型结构的对象结构
19.代理模式(本质:控制对象的访问)
和适配器模式的区别:
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.桥梁模式(分离抽象与实现)
抽象部分和实现部分分离,可以独立的变化,二个纬度以上变化的时候
java中的JDBC
21.装饰模式(本质:动态组合)
动态的生成子类
DataInputStream din = new DataInputStream( new BufferedInputStream( new FileInputStream("IOTest.txt") ) );
AOP:
22.门面模式(外观模式Facade,本质:封装交互,简化调用)
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(); } }
体现了最少知识原则
23.享元模式(本质:分离与共享)
//缓存菜单 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;
做一个享元工厂缓存菜单
(分离与共享)
//网站 flyweight abstract class WebSite { public abstract void Use(User user); }
//具体的网站 concreteflyweight class ConcreteWebSite : WebSite { private string name = ""; public ConcreteWebSite(string name) { this.name = name; } public override void Use(User user) { Console.WriteLine("网站分类:" + name + " 用户:" + user.Name); } }
//网站工厂flyweightfactory class WebSiteFactory { private Hashtable flyweights = new Hashtable(); //获得网站分类 public WebSite GetWebSiteCategory(string key) { if (!flyweights.ContainsKey(key)) flyweights.Add(key, new ConcreteWebSite(key)); return ((WebSite)flyweights[key]); } //获得网站分类总数 public int GetWebSiteCount() { return flyweights.Count; } }