zoukankan      html  css  js  c++  java
  • Spring.NET依赖注入 制作可替换的算法

    1. 配置文件

    <configuration>
      <configSections>
        <sectionGroup name="spring">
          <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
          <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
      </configSections>

      <spring>
        <context>
          <resource uri="config://spring/objects"/>
        </context>
        
        <objects>
          <!-- Default Implement -->
          <object name="algHello" type="CsharpTrainer.Strategy.Hello.EngHello, CsharpTrainer.Strategy">
          </object>
          <!-- Extended Implement -->
          <!--<object name="algHello" type="CsharpTrainer.Strategy.Hello.ChnHello, CsharpTrainer.Strategy">
          </object>
    -->
        </objects>
      </spring>

      ...
    </configuration>

    2. 算法接口

      策略接口

    public interface IStrategy
        {
            void Execute();
        }

    算法1

    public class EngHello : IStrategy
        {
            public void Execute()
            {
                Console.WriteLine("Hello, World!");
            }
        }

    算法2

    public class ChnHello : IStrategy
        {
            public void Execute()
            {
                Console.WriteLine("你好, 世界!");
            }
        }

    3. Spring调用端

    public class HelloAlgorithm
        {
            public static void SayHello()
            {
                //从config文件中取得程序集信息
                IApplicationContext context = ConfigurationManager.GetSection("spring/context"as IApplicationContext;

                //调用方法
                IStrategy alg = context.GetObject("algHello"as IStrategy;
                alg.Execute();
            }

    4. 运行和替换

      运行程序,结果是Hello, World

      如果我们把算法配置换成

    <object name="algHello" type="CsharpTrainer.Strategy.Hello.ChnHello, CsharpTrainer.Strategy">
    </object>

      结果将是: 你好, 世界


       

    技术改变世界
  • 相关阅读:
    BZOJ4669 抢夺(网络流)
    三元环&四元环计数
    P3768 简单的数学题(杜教筛)
    P1829 [国家集训队]Crash的数字表格(莫比乌斯反演)
    P5221 Product(欧拉函数)
    P3704 [SDOI2017]数字表格(莫比乌斯反演)
    P4619 [SDOI2018]旧试题
    Loj6102. 「2017 山东二轮集训 Day1」第三题(min-max 反演)
    Leetcode220 存在重复元素III
    Leetcode219 存在重复元素II 滑动窗口
  • 原文地址:https://www.cnblogs.com/davidgu/p/2526440.html
Copyright © 2011-2022 走看看