天天看點

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

            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>

  結果将是: 你好, 世界