• 设计模式漫谈之策略模式


    最近也是事多,压力也挺大的。烦事也多,所以又需要我写篇博客静静心,最近看了很多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();

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

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

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

  • 相关阅读:
    自己的思考
    spring MVC整合freemarker
    手把手教你搭建SpringMVC——最小化配置
    深入hibernate的三种状态
    maven 构建slf4j1.7.7之简单测试与源码解析
    maven 构建slf4j1.7.7之简单测试与源码解析
    (转)URI和URL的区别
    Spring缓存机制的理解
    (转)oracle 高水位线详解
    (转)PL/SQL Developer使用技巧、快捷键
  • 原文地址:https://www.cnblogs.com/wang-charle/p/9478780.html
Copyright © 2020-2023  润新知