Unity入门之一(StopLight关于Unity在应用程序中的使用)

前面写了一篇 Unity入门。写的比较仓促,所以东西比较粗糙,正如 戏水3 所说,没起到入门的作用。
本文就从 Unity中的QuickStart中关于StopLight的例子描述下Unity在程序开发中如何使用吧。

摘要:
交通灯Demo主要介绍如何在你的应用程序中使用Unity,用户界面是一个比较简单的WinForm程序,旨在显示
交通灯的示意,红黄绿,你可以设置它们依次显示的周期。 Form窗体界面如下图:


 

类关系图如下图:

 


 

向Unity容器注册服务:
在此Demo中主要使用了2个Service,即注册实现两个接口的服务。具体事例类
容器根据需要自动创建实例。

主要两个接口是 ILoger,IStoplightTimer ,ILoger具体实现 TraceLogger,NullLogger
IStoplightTimer 实现 RealTimeTimer
Code:

 

ContractedBlock.gif ExpandedBlockStart.gif ILogger
namespace StopLight.ServiceInterfaces
{
    
public interface ILogger
    {
        
void Write(string message);
    }
}

 

 

ContractedBlock.gif ExpandedBlockStart.gif TraceLogger
using System;
using System.Diagnostics;
using StopLight.ServiceInterfaces;

namespace StopLight.ServiceImplementations
{
    
internal class TraceLogger : ILogger
    {
        
public StopLight.ServiceInterfaces.ILogger ILogger
        {
            
get
            {
                
throw new System.NotImplementedException();
            }
            
set
            {
            }
        }
        
#region ILogger Members

        
public void Write(string message)
        {
            Trace.WriteLine(
string.Format("{0}: {1}",
                                          DateTime.Now,
                                          message));
        }

        
#endregion
    }
}

 

ContractedBlock.gif ExpandedBlockStart.gif IStoplightTimer
using System;

namespace StopLight.ServiceInterfaces
{
    
public interface IStoplightTimer
    {
        TimeSpan Duration { 
getset; }
        
void Start();
        
event EventHandler Expired;
    }
}

 

ContractedBlock.gif ExpandedBlockStart.gif RealTimeTimer
using System;
using System.Windows.Forms;
using StopLight.ServiceInterfaces;

namespace StopLight.ServiceImplementations
{
    
internal class RealTimeTimer : IStoplightTimer
    {
        
private Timer timer;

        
public event EventHandler Expired;

        
public RealTimeTimer()
        {
            timer 
= new Timer();
            timer.Tick 
+= OnTick;
        }

        
public TimeSpan Duration 
        {
            
get { return TimeSpan.FromMilliseconds(timer.Interval); }
            
set { timer.Interval = (int)value.TotalMilliseconds; }
        }

        
public void Start()
        {
            timer.Start();
        }

        
private void OnTick(object sender, EventArgs e)
        {
            timer.Stop();
            OnExpired(
this);
        }

        
protected virtual void OnExpired(object sender)
        {
            EventHandler handlers 
= Expired;
            
if(handlers != null)
            {
                handlers(
this, EventArgs.Empty);
            }
        }
    }
}

 

 

我们借用Unity,即可以在容器中注册这两个服务:

 

ContractedBlock.gif ExpandedBlockStart.gif Main
Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false);

            IUnityContainer container 
= new UnityContainer()
                .RegisterType
<ILogger, TraceLogger>()
                .RegisterType
<IStoplightTimer, RealTimeTimer>();

            Application.Run(container.Resolve
<StoplightForm>());

 

 

这样我们就在容器中建立了两个关系映射,即ILogger的实例TraceLogger 和
IStoplightTimer的实例 RealTimeTimer。
注意:以上说的实例还不够确切,只是一个关系映射,如果我们从容器中想要使用ILogger时,通过Resolve时,容器此时才会生成
ILogger的TranceLogger的实例。

在容器中注册了两个接口的映射关系后,我们还需要为我们的程序依赖注入一个
子对象或者暴露一个入口供我们去运行这个程序,即还要有用户界面供外部调用。
继承Windows.Form 的StoplightForm就做我们的主显示窗体吧,为确保所有的对象都是依赖注入的,我们就可以在
Program 类中通过Resolve方法生成StoplightForm,并显示。
Code:

Application.Run(container.Resolve<StoplightForm>());


使用MVP模式:


当Demo运行时,它会加载我们的用户接口,StoplightForm 窗体,该窗体实现了MVP模式, MVP模式具体如何实现在此不做多讲,有兴趣的可以去
TerryLee 的博客 ,那里面有详细的介绍。

实现了MVP模式,那么它就需要暴露一个 属性(类对象)给调用者。这个类对象即是 StoplightPresenter,这Form窗体使用属性的
Setter方法获取StoplightPresenter 实例设置presenter。

public partial class StoplightForm : Form, IStoplightView
{
  private StoplightPresenter presenter;
  [Dependency]
  public StoplightPresenter Presenter
  {
    get { return presenter; }
    set
    {
      presenter = value;
      presenter.SetView(this);
    }
  }
  ...

注意: 必须确保Untity在创建StoplightForm 之前创建Presenter,这样依赖注入的类才能被注入,生成StoplightPresenter。


通过属性 Setter注入业务组件:

private Stoplight stoplight;

 

[Dependency]
public Stoplight Stoplight
{
  get { return stoplight; }
  set { stoplight = value; }
}

 

同样 Presenter 也需要一个依赖对象StoplightSchedule ,Code:


private StoplightSchedule schedule;

[Dependency]
public StoplightSchedule Schedule
{
  get { return schedule; }
  set { schedule = value; }
}


至此,此Demo需要依赖注入的对象已完成,在Unity已经成功生成了个对象之间的映射关系。


后注:

Demo旨在演示通过Unity依赖注入对象,来实现我们想要的功能。 比如ILogger。TraceLogger是我们在程序初期就已经设计好了,
并确定使用它。那么我们在一开始就可以通过Untity的RegisteType进行关系映射。 但是 有时需求并不是在一开始就能取诶的那个。
比如,在后期程序中的ILogger接口我们需要使用FileLogger记录,那我们就要重新修改代码,重新编译了。

其实Untity中我们可以通过 配置文件 进行动态注册。需要使用哪种日志直接通过修改配置文件就可以了。

下篇将介绍如何使用配置文件进行Unity动态注册及映射关系。 

不足之处,请包涵。谢谢

Demo代码:下载

 

 


 

转载于:https://www.cnblogs.com/liujian969/archive/2009/01/19/1378116.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值