静态工厂方法创建对象

 静态工厂方法创建对象
 对于这种方式,我们只需指定 "factory-method" 即可,需要注意的是所指定的方法必须是静态方法
using System;
using System.Collections;
using System.Text;
using System.Threading;
using Spring.Core;
using Spring.Context;
using Spring.Context.Support;
using System.Configuration;
namespace ConsoleApplication1.SpringNet
{

 /// <summary>
 /// 静态工厂方法创建对象
 /// 对于这种方式,我们只需指定 "factory-method" 即可,需要注意的是所指定的方法必须是静态方法
 /// </summary>
 public class HelloWorld
 {
  private HelloWorld()
  {
  }

  public static HelloWorld Create()
  {
   return new HelloWorld();
  }
  public override  string ToString()
  {
//   Console.WriteLine("这是调用静态工厂方法创建对象");
   return "这是调用静态工厂方法创建对象";
  }

 }

 public class Program
 {
  static void Main()
  {
   IApplicationContext ctx = ConfigurationSettings.GetConfig("spring/context") as IApplicationContext;

   object o = ctx.GetObject("HelloWorld");
//   object o2 = ctx.GetObject("HelloWorld");
   Console.WriteLine(o.ToString());
//   Console.WriteLine(object.ReferenceEquals(o, o2)); // output: true
   Console.ReadLine();
  }
 }
}

<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 xmlns="http://www.springframework.net">
   <object id="HelloWorld" type="ConsoleApplication1.SpringNet.HelloWorld, test1" factory-method="Create">  
            </object>
  </objects>
 </spring>
</configuration>

 

posted @ 2007-06-27 15:38  每天积累一点  阅读(498)  评论(0编辑  收藏  举报