设计模式漫谈之策略模式

最近也是事多,压力也挺大的。烦事也多,因此又须要我写篇博客静静心,最近看了不少asp.net底层代码发现大牛真的多,天外有天人外有人。算法

想看底层代码须要5年的工做经验,精通语法,精通编程思想。而编程思想和语法能够经过设计模式来学习。编程

 

在C语言中,能够根据类型,申请内存空间。反射也是一样的道理,根据类型申请空间。设计模式

 

接口至关于C语言中的申明,框架

也是一种封装,好比,我须要A方法,B实现的时候,把A方法所须要的数据封装隐藏.asp.net

 

封装不一样的状况,提供统一接口,不管对象是关联关系,仍是依赖关系,都是对象之间互相访问(便可以找到对方的对象空间)。对象不销毁,对象之中的数据仍在。ide

如今面向对象的框架大部分都是,工厂+反射+接口+代理。基本成套路了。直接上例子,我来解释:函数

//抽象类,表面,我只须要你公开acceptCash(算法),程序即算法+数据,至于数据,我不须要你公开,你统一封装隐藏。学习

abstract class CashSuper
{
public abstract double acceptCash(double money);
}this

//抽象的实现对象.net

class CashReturn : CashSuper
{

//始终不须要对外公开,可是对类内部公开
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
//构造函数
public CashReturn(string moneyCondition,string moneyReturn)
{
this.moneyCondition = double.Parse(moneyCondition);
this.moneyReturn = double.Parse(moneyReturn);
}

重写的对外公开类

public override double acceptCash(double money)
{
double result = money;
if (money >= moneyCondition)
result=money- Math.Floor(money / moneyCondition) * moneyReturn;

return result;
}
}

//上下文类。

//上下文意思是百晓生,百事通,知道全部的对象,那就须要能访问到其余对象的内存空间

class CashContext
{

//关联对象,知道对象cs,对象不消亡,对象空间中的数据一直存在。
private CashSuper cs;

public void setBehavior(CashSuper csuper)
{
this.cs = csuper;
}

//又对外统一提供接口

public double GetResult(double money)
{
return cs.acceptCash(money);
}
}

//客户端(如今系统的模型有事件模型,数据模型,请求处理响应模型等)

CashContext cc = new CashContext();

DataRow dr = ((DataRow[])ds.Tables[0].Select("name='" + cbxType.SelectedItem.ToString()+"'"))[0];
//反射的参数是object[]
object[] args =null;

if (dr["para"].ToString() != "")
args = dr["para"].ToString().Split(',');

cc.setBehavior((CashSuper)Assembly.Load("商场管理软件").CreateInstance("商场管理软件." + dr["class"].ToString(), false, BindingFlags.Default, null, args, null, null));

double totalPrices = 0d;

//调上下文的统一接口
totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text));
total = total + totalPrices;
lbxList.Items.Add("单价:" + txtPrice.Text + " 数量:" + txtNum.Text + " "+cbxType.SelectedItem+ " 合计:" + totalPrices.ToString());
lblResult.Text = total.ToString();

 

总结,策略模式就是抽象,接口,反射的具体应用。根据不一样的策略生成不一样的对象,调用多态的方法。

 

编程思想,能够从设计模式中学到,也能从设计模式中学到一种语言的语法。

 

睡觉了,不写了。下次见!

相关文章
相关标签/搜索