站长信息
jeffery.xu
jeffery.xu

软件工程师

欢迎访问我的个人笔记网站!我是一名热爱技术的开发者,专注于Web开发和技术分享。

811495111@qq.com
18521510875
筛选

个人笔记

运费模板XML
工作笔记
<GridViewConfig xmlns="http://www.mobizone.cn/Configuration/GridViewConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<GridViewName>TBFreightTemplate</GridViewName>
<GridViewBase>
<!--列表ID-->
<GridViewId>ID00423D3CB9574D98A2898BAE9CC82009</GridViewId>
<!--列表Ng-Mode指令-->
<NgModel>NM00423D3CB9574D98A2898BAE9CC82009</NgModel>
<!--表单请求方式-->
<Method>POST</Method>
<!--表单请求数据源路径-->
<URL>Gridview/LoadData</URL>
<!--启用缓存-->
<Cache>false</Cache>
<!--是否单选-->
<SingleSelect>true</SingleSelect>
<!--分页-->
<Pagination>true</Pagination>
<!--表格样式-->
<Classes>table table-hover table-no-bordered</Classes>
<!--排序方式-->
<Sort>desc</Sort>
<!--默认排序字段-->
<SortName>a_CreateTime</SortName>
<!--是否显示行间隔色-->
<Striped>true</Striped>
<!--表格汉化-->
<Locales>zh-US</Locales>
<!--显示搜索框-->
<Search>false</Search>
<!--是否启用所有列-->
<ShowColumns>true</ShowColumns>
<!--是否启用刷新事件-->
<ShowRefresh>true</ShowRefresh>
<!--最少允许的列数-->
<MinimumCountColumns>2</MinimumCountColumns>
<!--是否显示导出-->
<ShowExport>true</ShowExport>
<!--basic', 'all', 'selected'-->
<ExportDataType>all</ExportDataType>
<!--是否显示详细视图和列表视图的切换按钮-->
<ShowToggle>true</ShowToggle>
<!--工具按钮用哪个容器-->
<!--<Toolbar>#toolbar</Toolbar>  -->
<!--分页大小-->
<PageSize>20</PageSize>
<PageNumber>1</PageNumber>
<!--<pageList>[10, 20, 50, 100, 200, 500]</pageList>-->
<!--标识哪个字段为id主键-->
<IdField>a_ID</IdField>
<!--针对弹出框放大镜的选择字段-->
<GridPickerSelectField>a_TemplateName</GridPickerSelectField>
<!--下拉框是单选框-->
<SelectItemName>a_ID</SelectItemName>
<!--刷新事件必须设置-->
<Silent>true</Silent>
<!--点击行即可选中单选/复选框-->
<ClickToSelect>true</ClickToSelect>
<!--参数格式,发送标准的RESTFul类型的参数请求-->
<QueryParamsType>limit</QueryParamsType>
<!--参数-->
<!--<QueryParams>$.queryParams</QueryParams>  -->
<!--表单列-->
<SidePagination>server</SidePagination>
<!--列表第一列配置-->
<FistColumn checkbox="true" align="center"/>
</GridViewBase>
<ColumnList>
<Column field="a_ID" title="ID" align="left" sortable="false" formatter="" visible="false" class="" level="1" notExport="true"></Column>
<Column field="a_TemplateName" title="模板名称" align="left" sortable="true" formatter="" visible="true" class="" level="2" gridPickerShow="true"/>
<Column field="b_BigName" title="大区" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="b_DiquName" title="地区" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="b_ProviceName" title="省份" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="b_CityName" title="城市" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="b_DName" title="区县" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="b_Code" title="门店编码" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="b_Name" title="门店名称" align="left" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="a_DeliveryMethod" title="配送方式值" align="center" sortable="true" formatter="" visible="false" notExport="true" class="" level="3" gridPickerShow="true"/>
<Column field="a_DeliveryMethodText" title="配送方式" align="center" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="a_TemplateType" title="模板类型值" align="center" sortable="true" formatter="" visible="false" notExport="true" class="" level="3" gridPickerShow="true"/>
<Column field="a_TemplateTypeText" title="模板类型" align="center" sortable="true" formatter="" visible="true" class="" level="3" gridPickerShow="true"/>
<Column field="a_IsFreeShipping" title="是否包邮值" align="center" sortable="true" formatter="" visible="false" notExport="true" class="" level="4" gridPickerShow="true"/>
<Column field="a_IsFreeShippingText" title="是否包邮" align="center" sortable="true" formatter="" visible="true" class="" level="4" gridPickerShow="true"/>
<Column field="a_FreeShippingMoney" title="免邮金额" align="right" sortable="true" formatter="" visible="true" class="" level="4" gridPickerShow="true"/>
<Column field="a_FreeShippingNum" title="免邮数量" align="right" sortable="true" formatter="" visible="true" class="" level="4" gridPickerShow="true"/>
<Column field="a_IsDefault" title="默认" align="center" sortable="true" formatter="" visible="false" notExport="true" class="" level="5" gridPickerShow="true"/>
<Column field="a_IsDefaultText" title="默认模板" align="center" sortable="true" formatter="" visible="true" class="" level="5" gridPickerShow="true"/>
<Column field="a_TemplateStatus" title="模板状态值" align="center" sortable="true" formatter="" visible="false" notExport="true" class="" level="6" gridPickerShow="true"/>
<Column field="a_TemplateStatusText" title="模板状态" align="center" sortable="true" formatter="" visible="true" class="" level="6" gridPickerShow="true"/>
<Column field="a_ReturnValue" title="运费方式值" align="center" sortable="true" formatter="" visible="false" notExport="true" class="" level="6" gridPickerShow="true"/>
<Column field="a_ReturnValueText" title="运费方式" align="center" sortable="true" formatter="" visible="true" class="" level="6" gridPickerShow="true"/>
<Column field="a_CreateTime" title="创建时间" align="left" sortable="true" formatter="formatterDatetime" visible="true" class="" level="33" gridPickerShow="true" notExport="true"/>
<Column field="cu_ChineseName" title="创建人" align="left" sortable="true" formatter="" visible="true" class="" level="33" gridPickerShow="true"/>
<Column field="a_ModifyTime" title="修改时间" align="left" sortable="true" formatter="formatterDatetime" visible="true" class="" level="33" gridPickerShow="true" notExport="true"/>
<Column field="mu_ChineseName" title="修改人" align="left" sortable="true" formatter="" visible="true" class="" level="33" gridPickerShow="true"/>
</ColumnList>
<TableMapping tableName="V_TBFreightTemplate" tableFixName="a" title="运费模板管理">
<Relations>
<JoinTable tableName="V_TBstoreInfo" tableFixName="b" Condition="a.FK_TBStore_ID=b.ID" type="Left_Join" level="1"/>
<!--关联创建用户-->
<JoinTable tableName="cu_SystemUser" tableFixName="cu" Condition="a.FK_SystemUser_Create_ID=cu.id" type="Left_Join" level="1"/>
<!--关联修改用户-->
<JoinTable tableName="mu_SystemUser" tableFixName="mu" Condition="a.FK_SystemUser_Modify_ID=mu.id" type="Left_Join" level="1"/>
</Relations>
<!--附加条件语句-->
<QueryWhereClause><![CDATA[a.IsDelete=0]]></QueryWhereClause>
</TableMapping>
<SearchForm isFixedPanel="true">
<FormController>FormController</FormController>
<ElementList>
<!--模板名称-->
<Element elementType="TextBox" dataType="" required="false" name="a_TemplateName" model="a_TemplateName" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="模板名称" lableEndText="" placeholder="请输入模板名称" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_BigName" model="b_BigName" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="大区" lableEndText="" placeholder="" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_DiquName" model="b_DiquName" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="地区" lableEndText="" placeholder="" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_ProviceName" model="b_ProviceName" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="省份" lableEndText="" placeholder="" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_CityName" model="b_CityName" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="城市" lableEndText="" placeholder="" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_DName" model="b_DName" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="区县" lableEndText="" placeholder="" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_Code" model="b_Code" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="门店编码" lableEndText="" placeholder="" defaultValue=""/>
</Element>
<Element elementType="TextBox" dataType="" required="false" name="b_Name" model="b_Name" fullRow="false" searchType="Like">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control " inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="门店名称" lableEndText="" placeholder="" defaultValue=""/>
</Element>
 
<!--配送方式-->
<Element elementType="multiple" dataType="" required="false" name="a_DeliveryMethod" model="a_DeliveryMethod" fullRow="false" validateType="">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control" inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="配送方式" lableEndText="" placeholder="" defaultValue=""/>
<SelectItemList multipleChoice="false">
<SelectItem text="快递" value="1" />
<SelectItem text="自提" value="2" />
<SelectItem text="同城配送" value="3" />
<SelectItem text="物流" value="4" />
</SelectItemList>
</Element>
 
<!--模板类型-->
<Element elementType="multiple" dataType="" required="false" name="a_TemplateType" model="a_TemplateType" fullRow="false" validateType="">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control" inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="模板类型" lableEndText="" placeholder="" defaultValue=""/>
<SelectItemList multipleChoice="false">
<SelectItem text="按件数" value="2" />
<!--<SelectItem text="按重量" value="2" />
<SelectItem text="按体积" value="3" />-->
</SelectItemList>
</Element>
 
<!--模板状态-->
<Element elementType="multiple" dataType="" required="false" name="a_TemplateStatus" model="a_TemplateStatus" fullRow="false" validateType="">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control" inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="模板状态" lableEndText="" placeholder="" defaultValue=""/>
<SelectItemList multipleChoice="false">
<SelectItem text="启用" value="1" />
<SelectItem text="禁用" value="0" />
</SelectItemList>
</Element>
<!--是否免邮-->
<Element elementType="multiple" dataType="" required="false" name="a_IsFreeShipping" model="a_IsFreeShipping" fullRow="false" validateType="">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control" inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="是否包邮" lableEndText="" placeholder="" defaultValue=""/>
<SelectItemList multipleChoice="false">
<SelectItem text="是" value="1" />
<SelectItem text="否" value="0" />
</SelectItemList>
</Element>
<!--是否默认模板-->
<Element elementType="multiple" dataType="" required="false" name="a_IsDefault" model="a_IsDefault" fullRow="false" validateType="">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control" inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="默认模板" lableEndText="" placeholder="" defaultValue=""/>
<SelectItemList multipleChoice="false">
<SelectItem text="是" value="1" />
<SelectItem text="否" value="0" />
</SelectItemList>
</Element>
 
<!--运费方式-->
<Element elementType="multiple" dataType="" required="false" name="a_ReturnValue" model="a_ReturnValue" fullRow="false" validateType="">
<StyleClass modeClass="col-sm-3" labelBeforeClass="col-sm-4 control-label" labelEndClass="" inputClass="form-control" inputParentClass="col-sm-8" />
<ElementTextInfo lableBeforeText="运费方式" lableEndText="" placeholder="" defaultValue=""/>
<SelectItemList multipleChoice="false">
<SelectItem text="买家承担" value="1" />
<SelectItem text="卖家承担" value="0" />
</SelectItemList>
</Element>
 
</ElementList>
</SearchForm>
<ButtonList>
<Button name="btn_delete" text="删除" class="btn btn-default" spanClass="glyphicon glyphicon-remove" level="2"></Button>
<Button name="btn_custom_use" text="启用\禁用" class="btn btn-outline-primary" spanClass="glyphicon glyphicon-file" level="8"></Button>
</ButtonList>
<ParameterList>
<!---外部关联参数-->
<outParameter>template_name,template_id</outParameter>
<!---如果存在直接调用使用-->
<innerParameter>template_id=1 and template_name='标准模板'</innerParameter>
<!---静态参数,如果存在直接调用使用-->
<staticParam><![CDATA[{a.IsDelete=0}]]></staticParam>
</ParameterList>
</GridViewConfig>
小河马启用禁用运费模板js
工作笔记
button_custom_submit: function (t) {
    var body = t.RequestButton;
    switch (body.name) {
        case "btn_custom_use"://启用/禁用
            var dt = mzServer.selectRow();
            if (dt.ResponseMessage.Success) {
                if (dt.Stats.length < 1) {
                    $scope.view.submit.Fn.loading(t.RequestButton.name, false);
                    mzServer.Msg.error("请选择一条数据");

                    return;
                }
                debugger;
                $scope.view.submit.Fn.loading(t.RequestButton.name, false);
                var state = dt.Stats[0].a_TemplateStatus; var tip = "";
                if (state == 1) {
                    state = 0; tip = "禁用";
                } else {
                    state = 1; tip = "启用";
                }
                mzServer.confirm('确定' + tip + '吗?').result.then(function (isconfirm) {
                    debugger;
                    if (isconfirm) {
                        var data = {};
                        var Info = {};
                        Info.a_ID = dt.Stats[0].a_ID;
                        Info.a_Status = state;
                        data.ConfigType = "view";
                        data.OpType = "query";
                        data.ConfigName = "TBFreightTemplate";
                        data.RequestBody = JSON.stringify(Info);
                        data.SpecialParameter = "ForbidOrUse";
                        data.url = "gridview/LoadData";
                        mzServer.postData(data).then(
                            function (response) {
                                console.log(response);
                                if (response.data.ResponseMessage.Success) {
                                    mzServer.Msg.success(tip+"成功!");
                                    angular.element("table[for='TBFreightTemplate']").bootstrapTable('refresh');
                                } else {
                                    mzServer.Msg.error(response.data.ResponseMessage.ErrorMessage);
                                }
                            }, function (error) {
                                mzServer.Msg.error(error);
                            });

                    }
                });
            }
            else {
                $scope.view.submit.Fn.loading(t.RequestButton.name, false);
                mzServer.Msg.error(dt.ResponseMessage.ErrorMessage);
            }
            break;

        default:
            mzServer.Msg.error("无效的事件");
            break;
    }

},
运费模板requestBody记录
工作笔记
//requestbody 详解
// {
//         // ========== 运费模板主表字段 (TBFreightTemplate) ==========
//         "ID": "运费模板ID", // 可选,有ID,则为EDITE,无为ADD
//         "TemplateName": "标准运费模板", // 必填 - 模板名称(唯一一个必须填写的)
//         "FK_TBMerchant_ID": "12345678-4115-11F0-98EC-0242AC110004", // 可选 - 关联商户ID
//         "DeliveryMethod": 1, // 可选 - 配送方式(1-快递,2-自提,3-同城配送,4-不配送)
//         "FK_TBStore_ID": "971A17B6-406B-11F0-98EC-0242AC110004", // 可选 - 关联门店ID
//         "TemplateType": 1, // 可选 - 模板类型(1-按件数,2-按重量,3-按金额) 默认1
//         "IsFreeShipping": false, // 可选 - 是否包邮(true/false) 默认false
//         "FreeShippingMoney": 100.00, // 可选 - 包邮金额 默认false
//         "FreeShippingNum": 20, // 可选 - 包邮数量  默认false
//         "IsDefault": true, // 可选 - 是否默认模板(true/false) 默认false
//         "IsAllRegion": true, // 可选 - 是否全国配送(true/false) 默认true
//         "FreeShippingCondition": 2, // 可选 - 包邮条件类型(1-满件数包邮,2-满金额包邮,3-满重量包邮)
//         "FreeShippingValue": 99.00, // 可选 - 包邮条件值
//         "ReturnValue": 0, // 可选 - 退货运费(0-卖家承担,1-买家承担)
//         "TemplateStatus": 1, // 可选 - 模板状态(0-禁用,1-启用) 默认1
//         "Sort": 10, // 可选 - 排序
//         "Memo": "这是标准运费模板的备注信息", // 可选 - 备注
//         // ========== 配送区域数组 (TBFreightTemplateRegion) ==========
//         "regions": [
//             {
//                 // 区域表字段
//                 "ID": "运费区域ID", // 可选,有ID,则为EDITE,无为ADD
//                 "RegionName": "江浙沪地区", // 可选 - 配送区域名称
//                 "IsFreeShipping": false, // 可选 - 是否包邮(true/false) 默认false
//                 "FreeShippingMoney": 100.00, // 可选 - 包邮金额
//                 "FreeShippingNum": 20, // 可选 - 包邮数量  
//                 "DeliveryType": 1, // 可选 - 配送类型(1-配送,2-不配送)
//                 "FirstUnit": 1, // 可选 - 首件/首重/首体积 默认1
//                 "FirstPrice": 8.00, // 可选 - 首件/首重/首体积价格 默认0
//                 "ContinueUnit": 1, // 可选 - 续件/续重/续体积 默认1
//                 "ContinuePrice": 5.00, // 可选 - 续件/续重/续体积价格 默认0
//                 // 区域表可选字段
//                 "ProvIds": "[\"82AEABFB-D580-4C2F-BF5C-02F5B7D6DDC2\",\"F6201801-28BC-442B-83E3-05D1C3604075\",\"3DDAD486-8C24-44AF-849D-062BF506FFC2\"]", // 可选 - 省份ID列表(JSON格式)
//                 "ProvNames": "北京,天津,河北省", // 可选 - 省份名称
//                 "CityIds": [], // 可选 - 城市编码列表(JSON格式)
//                 "DistrictIds": [], // 可选 - 区县编码列表(JSON格式)
//                 "FreeShippingCondition": 2, // 可选 - 区域包邮条件类型(1-满件数,2-满金额,3-满重量)
//                 "FreeShippingValue": 88.00, // 可选 - 区域包邮条件值
//                 "IsRegionFree": false, // 可选 - 该区域是否包邮 默认false
//                 "Sort": 1, // 可选 - 排序
//                 "Memo": "江浙沪地区配送", // 可选 - 备注
//                 // ========== 计费详情数组 (TBFreightTemplateDetail) ==========
//                 "details": [
//                     {
//                         // 详情表字段 - 现在全部为可选
//                         "MinValue": 1.000, // 可选 - 最小值(件数/重量/体积)
//                         "MaxValue": 5.000, // 可选 - 最大值(件数/重量/体积)
//                         "Price": 8.00, // 可选 - 该区间价格
//                         "PriceType": 1, // 可选 - 价格类型(1-固定价格,2-每单位价格)
//                         "Sort": 1, // 可选 - 排序
//                         "Memo": "1-5件商品运费" // 可选 - 备注
//                     },
//                     {
//                         "MinValue": 6.000,
//                         "MaxValue": 10.000,
//                         "Price": 12.00,
//                         "PriceType": 1,
//                         "Sort": 2,
//                         "Memo": "6-10件商品运费"
//                     }
//                 ]
//             },
//             {
//                 // 第二个配送区域示例
//                 "RegionName": "其他地区",
//                 "IsFreeShipping": false, // 可选 - 是否包邮(true/false) 默认false
//                 "FreeShippingMoney": 100.00, // 可选 - 包邮金额
//                 "FreeShippingNum": 20, // 可选 - 包邮数量  
//                 "DeliveryType": 1,
//                 "FirstUnit": 1,
//                 "FirstPrice": 12.00,
//                 "ContinueUnit": 1,
//                 "ContinuePrice": 8.00,
//                 "ProvIds": "[\"88131078-7258-4846-BD02-3E31A25F1336\"]",
//                 "ProvNames": "江苏省", // 可选 - 省份名称
//                 "FreeShippingCondition": 2,
//                 "FreeShippingValue": 150.00,
//                 "IsRegionFree": false,
//                 "Sort": 2,
//                 "Memo": "其他地区配送",
//                 "details": [
//                     {
//                         "MinValue": 1.000,
//                         "MaxValue": 3.000,
//                         "Price": 12.00,
//                         "PriceType": 1,
//                         "Sort": 1,
//                         "Memo": "1-3件商品运费"
//                     }
//                 ]
//             }
//         ]
//     }
// }
工厂模式
设计模式
工厂模式是一种创建对象的设计模式,它将对象的创建和使用分离,使得代码更加灵活、可维护和可扩展。这种模式特别适用于以下场景:
  • 当一个类不知道它所必须创建的对象的类时
  • 当一个类希望由它的子类来指定所创建的对象时
  • 当将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化时
    using System;
    
    // 定义产品接口
    public interface IProduct
    {
        void Operation();
    }
    
    // 具体产品A
    public class ConcreteProductA : IProduct
    {
        public void Operation()
        {
            Console.WriteLine("ConcreteProductA Operation");
        }
    }
    
    // 具体产品B
    public class ConcreteProductB : IProduct
    {
        public void Operation()
        {
            Console.WriteLine("ConcreteProductB Operation");
        }
    }
    
    // 简单工厂类
    public class SimpleFactory
    {
        public static IProduct CreateProduct(string type)
        {
            switch (type.ToLower())
            {
                case "a":
                    return new ConcreteProductA();
                case "b":
                    return new ConcreteProductB();
                default:
                    throw new ArgumentException("Invalid product type", nameof(type));
            }
        }
    }
    
    // 客户端代码
    class Program
    {
        static void Main()
        {
            // 使用简单工厂创建产品A
            IProduct productA = SimpleFactory.CreateProduct("A");
            productA.Operation();
    
            // 使用简单工厂创建产品B
            IProduct productB = SimpleFactory.CreateProduct("B");
            productB.Operation();
    
            try
            {
                // 尝试创建无效产品类型
                IProduct invalidProduct = SimpleFactory.CreateProduct("C");
                invalidProduct.Operation();
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }    

 

工厂模式的优点

  • 解耦对象的创建和使用:客户端不需要知道具体产品类的类名,只需要知道对应的参数即可。
  • 可扩展性好:在增加新的产品类时,只需要修改工厂类或者扩展工厂子类,符合开闭原则。
  • 便于代码维护:创建对象的逻辑集中在一个工厂类中,便于维护和修改。

工厂模式的缺点

  • 工厂类职责过重:简单工厂模式中,工厂类集中了所有产品的创建逻辑,一旦不能正常工作,整个系统都会受到影响。
  • 增加系统复杂度:如果产品种类过多,会导致工厂类变得庞大,增加系统的复杂度。
  • 违反开闭原则:在简单工厂模式中,每当增加新的产品时,都需要修改工厂类,这违反了开闭原则。

 

工厂模式在实际开发中应用广泛,特别是在需要创建大量对象、对象创建过程复杂或者需要根据不同条件创建不同类型对象的场景中。
依赖倒置原则(Dependency Inversion Principle, DIP)
设计模式
  1. 高层模块不应依赖低层模块,二者都应依赖抽象。
  2. 抽象不应依赖细节,细节应依赖抽象。
    示例
    # 反例:高层模块依赖低层模块
    class LightBulb:
        def turn_on(self):
            print("灯泡亮了")
    
    class Switch:
        def __init__(self):
            self.bulb = LightBulb()  # 直接依赖具体实现
    
    # 正例:依赖抽象
    from abc import ABC, abstractmethod
    
    class Switchable(ABC):
        @abstractmethod
        def turn_on(self):
            pass
    
    class LightBulb(Switchable):
        def turn_on(self):
            print("灯泡亮了")
    
    class Fan(Switchable):
        def turn_on(self):
            print("风扇转了")
    
    class Switch:
        def __init__(self, device: Switchable):
            self.device = device  # 依赖抽象而非具体实现
接口隔离原则(Interface Segregation Principle, ISP)
设计模式

客户端不应该被迫依赖它不需要的接口。应该把庞大的接口拆分成更小、更具体的接口。

# 反例:一个大而全的接口
class Worker:
    def work(self):
        pass
    def eat(self):
        pass

class Robot(Worker):
    def work(self):
        pass
    def eat(self):
        raise NotImplementedError("机器人不需要吃饭")  # 被迫实现不需要的方法

# 正例:拆分接口
class Workable:
    def work(self):
        pass

class Eatable:
    def eat(self):
        pass

class HumanWorker(Workable, Eatable):
    pass

class RobotWorker(Workable):
    pass
运费模块设计
新框架
  1. 运费模板表
    CREATE TABLE TBFreightTemplate (
        ID uniqueidentifier NOT NULL PRIMARY KEY DEFAULT NEWID(),           -- 主键ID
        TemplateName nvarchar(100) NOT NULL,                                 -- 模板名称
        FK_TBMerchant_ID uniqueidentifier NOT NULL,                         -- 关联商户ID
        FK_TBStore_ID uniqueidentifier,                                     -- 关联门店ID
        TemplateType tinyint NOT NULL DEFAULT 1,                            -- 模板类型(1-按件数,2-按重量,3-按金额)
        DeliveryMethod tinyint NOT NULL,                                     -- 配送方式(1-快递,2-自提,3-同城配送,4-不配送)
        IsFreeShipping bit NOT NULL DEFAULT 0,                              -- 是否包邮(0-否,1-是)
        IsDefault bit NOT NULL DEFAULT 0,                                   -- 是否默认模板(0-否,1-是)
        IsAllRegion bit NOT NULL DEFAULT 1,                                 -- 是否全国配送(0-否,1-是)
        FreeShippingCondition tinyint,                                      -- 包邮条件类型(1-满件数包邮,2-满金额包邮,3-满重量包邮)
        FreeShippingValue decimal(10,2),                                    -- 包邮条件值
        ReturnValue tinyint,                                                 -- 退货运费:0:卖家承担;1:买家承担
        TemplateStatus tinyint NOT NULL DEFAULT 1,                          -- 模板状态(0-禁用,1-启用)
        CreateTime datetime NOT NULL DEFAULT GETDATE(),                 -- 创建时间
        FK_SystemUser_Create_ID uniqueidentifier,                           -- 创建人ID
        ModifyTime datetime NOT NULL DEFAULT GETDATE(),                 -- 最后更新时间
        FK_SystemUser_Modify_ID uniqueidentifier,                           -- 最后更新人ID
        IsValid bit NOT NULL DEFAULT 1,                                     -- 是否有效(0-无效,1-有效)
        IsDelete bit NOT NULL DEFAULT 0,                                    -- 是否删除(0-未删除,1-已删除)
        FK_Systemuserdepartment_Create_ID uniqueidentifier,                 -- 创建部门ID
        Sort int DEFAULT 0,                                                  -- 排序
        Memo nvarchar(500),                                                  -- 备注
    );
    
    -- 运费模板配送区域表
    CREATE TABLE TBFreightTemplateRegion (
        ID uniqueidentifier NOT NULL PRIMARY KEY DEFAULT NEWID(),           -- 主键ID
        FK_TBFreightTemplate_ID uniqueidentifier NOT NULL,                  -- 关联运费模板ID
        RegionName nvarchar(100) NOT NULL,                                  -- 配送区域名称
        ProvIds nvarchar(max),                                               -- 省份编码列表(JSON格式)
        CityIds nvarchar(max),                                               -- 城市编码列表(JSON格式) 可为空
        DistrictIds nvarchar(max),                                           -- 区县编码列表(JSON格式) 可为空
        DeliveryType tinyint NOT NULL,                                       -- 配送类型(1-配送,2-不配送)
        FirstUnit int NOT NULL DEFAULT 1,                                   -- 首件/首重/首体积
        FirstPrice decimal(10,2) NOT NULL DEFAULT 0.00,                     -- 首件/首重/首体积价格
        ContinueUnit int NOT NULL DEFAULT 1,                                -- 续件/续重/续体积
        ContinuePrice decimal(10,2) NOT NULL DEFAULT 0.00,                  -- 续件/续重/续体积价格
        FreeShippingCondition tinyint,                                      -- 区域包邮条件类型(1-满件数包邮,2-满金额包邮,3-满重量包邮)
        FreeShippingValue decimal(10,2),                                    -- 区域包邮条件值
        IsRegionFree bit NOT NULL DEFAULT 0,                                -- 该区域是否包邮(0-否,1-是)
        CreateTime datetime NOT NULL DEFAULT GETDATE(),                 -- 创建时间
        FK_SystemUser_Create_ID uniqueidentifier,                           -- 创建人ID
        ModifyTime datetime NOT NULL DEFAULT GETDATE(),                 -- 最后更新时间
        FK_SystemUser_Modify_ID uniqueidentifier,                           -- 最后更新人ID
        IsValid bit NOT NULL DEFAULT 1,                                     -- 是否有效(0-无效,1-有效)
        IsDelete bit NOT NULL DEFAULT 0,                                    -- 是否删除(0-未删除,1-已删除)
        FK_Systemuserdepartment_Create_ID uniqueidentifier,                 -- 创建部门ID
        Sort int DEFAULT 0,                                                  -- 排序
        Memo nvarchar(500),                                                  -- 备注
    );
    
    -- 运费模板计费详情表
    CREATE TABLE TBFreightTemplateDetail (
        ID uniqueidentifier NOT NULL PRIMARY KEY DEFAULT NEWID(),           -- 主键ID
        FK_TBFreightTemplateRegion_ID uniqueidentifier NOT NULL,            -- 关联运费模板区域ID
        MinValue decimal(10,3) NOT NULL,                                    -- 最小值(件数/重量/体积)
        MaxValue decimal(10,3),                                             -- 最大值(件数/重量/体积)
        Price decimal(10,2) NOT NULL,                                       -- 该区间价格
        PriceType tinyint NOT NULL,                                         -- 价格类型(1-固定价格,2-每单位价格)
        CreateTime datetime NOT NULL DEFAULT GETDATE(),                 -- 创建时间
        FK_SystemUser_Create_ID uniqueidentifier,                           -- 创建人ID
        ModifyTime datetime NOT NULL DEFAULT GETDATE(),                 -- 最后更新时间
        FK_SystemUser_Modify_ID uniqueidentifier,                           -- 最后更新人ID
        IsValid bit NOT NULL DEFAULT 1,                                     -- 是否有效(0-无效,1-有效)
        IsDelete bit NOT NULL DEFAULT 0,                                    -- 是否删除(0-未删除,1-已删除)
        FK_Systemuserdepartment_Create_ID uniqueidentifier,                 -- 创建部门ID
        Sort int DEFAULT 0,                                                  -- 排序
        Memo nvarchar(500),                                                  -- 备注
    );
Json.ToJson乱码解决
编程技巧

  // 使用JsonConvert.SerializeObject保留中文
  var jsonSettings = new JsonSerializerSettings
  {
      StringEscapeHandling = StringEscapeHandling.Default
  };
  
  data.RequestBody = JsonConvert.SerializeObject(resultJson, jsonSettings);
  
  // 这里是关键 - 使用JsonConvert.SerializeObject来序列化整个data对象
  string postData = JsonConvert.SerializeObject(data, jsonSettings);
  
  // 使用序列化后的字符串而不是JSON.ToJSON(data)

 var content = HttpTools.PostHttpNHSHelp(url, postData, "同步答卷结果");

里氏替换原则(Liskov Substitution Principle, LSP)
设计模式

里氏替换原则(Liskov Substitution Principle, LSP)是面向对象设计的核心原则之一,由芭芭拉・利斯科夫(Barbara Liskov)在 1987 年提出。其核心思想是:子类对象必须能够替换掉它们的父类对象,而不影响程序的正确性。这意味着,子类应当遵循父类的契约,保持行为的一致性。

核心动机

  • 继承的正确性:确保子类不会破坏父类的原有功能。
  • 多态的可靠性:通过父类引用调用子类方法时,结果应符合预期。
  • 降低系统风险:避免因子类行为异常导致的潜在错误。

LSP 的关键要求

  1. 前置条件不能强化:子类方法的前置条件(输入参数)不能比父类更严格。
  2. 后置条件不能弱化:子类方法的后置条件(返回值)必须满足父类的要求。
  3. 不变式要保持:子类不能改变父类的不变量(如类的约束条件)。
  4. 异常要兼容:子类抛出的异常应当与父类一致或为其子类。

C# 示例:矩形与正方形问题

违反 LSP 的经典案例

假设我们有一个矩形类和一个正方形类,正方形继承自矩形:
// 基类:矩形
public class Rectangle
{
    public virtual double Width { get; set; }
    public virtual double Height { get; set; }

    public double Area() => Width * Height;
}

// 子类:正方形(错误设计)
public class Square : Rectangle
{
    // 正方形的宽和高必须相等
    public override double Width
    {
        get => base.Width;
        set
        {
            base.Width = value;
            base.Height = value;
        }
    }

    public override double Height
    {
        get => base.Height;
        set
        {
            base.Height = value;
            base.Width = value;
        }
    }
}

问题分析

这个设计违反了 LSP,因为:
  • 前置条件被强化:父类允许设置不同的宽和高,但子类强制二者相等。
  • 行为不一致:以下代码在使用父类时正常,但使用子类时会出错:
    public void TestRectangle(Rectangle rect)
    {
        rect.Width = 5;
        rect.Height = 10;
        Console.WriteLine(rect.Area()); // 预期输出50
    }
    
    // 测试
    var rectangle = new Rectangle();
    TestRectangle(rectangle); // 输出50,正确
    
    var square = new Square();
    TestRectangle(square);    // 输出100,错误!

遵循 LSP 的重构方案

方案 1:抽象公共接口

// 抽象接口:四边形
public interface IQuadrilateral
{
    double Width { get; }
    double Height { get; }
    double Area();
}

// 矩形实现
public class Rectangle : IQuadrilateral
{
    public double Width { get; set; }
    public double Height { get; set; }
    public double Area() => Width * Height;
}

// 正方形实现
public class Square : IQuadrilateral
{
    private double _side;
    
    public double Width
    {
        get => _side;
        set => _side = value;
    }
    
    public double Height
    {
        get => _side;
        set => _side = value;
    }
    
    public double Area() => _side * _side;
}

方案 2:组合而非继承

// 正方形包含一个矩形实例
public class Square
{
    private readonly Rectangle _rectangle = new Rectangle();
    
    public double Side
    {
        get => _rectangle.Width;
        set
        {
            _rectangle.Width = value;
            _rectangle.Height = value;
        }
    }
    
    public double Area() => _rectangle.Area();
}

另一个示例:银行账户与透支账户

违反 LSP 的设计

// 基类:银行账户
public class BankAccount
{
    protected double _balance;
    
    public virtual void Withdraw(double amount)
    {
        if (amount > _balance)
            throw new InvalidOperationException("余额不足");
        
        _balance -= amount;
    }
}

// 子类:透支账户(错误设计)
public class OverdraftAccount : BankAccount
{
    private double _overdraftLimit = 1000;
    
    // 重写取款方法,允许透支
    public override void Withdraw(double amount)
    {
        if (amount > _balance + _overdraftLimit)
            throw new InvalidOperationException("超过透支限额");
            
        _balance -= amount;
    }
}

问题分析

  • 前置条件被弱化:子类允许更多情况下的取款(透支),而父类不允许。
  • 行为不一致:依赖父类行为的代码(如检查余额)在使用子类时会失效。

LSP 的其他应用场景

  1. 集合类中的协变与逆变:确保泛型集合的类型安全。
  2. 事件处理:子类事件的参数应与父类兼容。
  3. 数据库操作:子类的查询条件不能比父类更严格。

总结

  • LSP 是继承的契约:子类必须遵守父类的行为约定。
  • 避免破坏父类行为:重写方法时不要改变原有的语义。
  • 优先使用组合:当继承导致 LSP 违反时,考虑使用组合或接口替代。
通过遵循 LSP,代码可以保持良好的可替换性和扩展性,降低系统的耦合度。
托管执行和CLI
编程技巧

处理器不能直接解释程序集。.NET程序集用的是另一种语言,即公共中间语言(Common Intermediate Language,CIL),或称中间语言(IL)。C#编译器将C#源代码转换成中间语言。为了将CIL代码转换成处理器能够理解的的机器码,还要完成一个额外的步骤(通常在运行时进行)。该步骤涉及C#程序执行的一个重要元素:VES(Virtual Execution System, 虚拟执行系统)。VES也称为”运行时“(runtime)。它根据需要编译CIL代码,这个过程称为即时编译JIT编译(just-in-time compilation)。如果代码在像”运行时“这样的一个”代理“的上下文中执行,那么就称为托管代码(managed code),在”运行时“的控制下执行的过程则称为托管执行(managed execution)。之所以称为”托管“,是因为”运行时“管理着诸如内存分配、安全性、JIT编译等方面,从而控制了主要的程序行为。执行时不需要”运行时“的代码则称为本机代码(native code)非托管代码(unmanaged code)