当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式漫谈之策略模式

设计模式漫谈之策略模式

2018年08月27日  | 移动技术网IT编程  | 我要评论

最近也是事多,压力也挺大的。烦事也多,所以又需要我写篇博客静静心,最近看了很多asp.net底层代码发现大牛真的多,天外有天人外有人。

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

 

在c语言中,可以根据类型,申请内存空间。反射也是同样的道理,根据类型申请空间。

 

接口相当于c语言中的申明,

也是一种封装,比如,我需要a方法,b实现的时候,把a方法所需要的数据封装隐藏.

 

封装不同的情况,提供统一接口,无论对象是关联关系,还是依赖关系,都是对象之间互相访问(即可以找到对方的对象空间)。对象不销毁,对象之中的数据仍在。

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

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

abstract class cashsuper
{
public abstract double acceptcash(double money);
}

//抽象的实现对象

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();

 

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

 

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

 

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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网