• CAB之Service


    CAB之Service
          如何使用Service?本文以一个例子来说明具体的设计过程。
          我们把方法的声明和实现分开来,所以用到了接口。
          1. 在接口文件中定义接口IGPSService,其中声明了两个方法GetLatitude和GetLongitude
           public interface IGPSService
         {
              int GetLatitude();
               int GetLongitude();
          }
          2. 接下来在类GPSService中实现这些方法
          [Service(typeof(IGPSService))]
         public class GPSService :
    IGPSService
         {
               public GPSService()
              {
                    MessageBox.Show("Service constructor");
              }

              public int GetLatitude()
              {
                    return 42;
               }

                public int GetLongitude()
               {
                    return 125;
                }
           }
         可以看到这个类的实现唯一与平常不同的就是开头处的 [Service(typeof(IGPSService))],
    这是利用Service属性来
    使得一个类自动注册成为WorkItem的Service成员。这样CAB就可以非常容易地找到这个服务的实现。用了type,就可
    以在不影响其他引用该服务的代码的前提下,改变这个服务的实现。
          注:有一种服务叫On-demand Service。当定义了很多服务时,如果在初始化的时候都load到内存中效率是很低的。在
    调用这个服务的时候才load到内存是比较好的方法。只要在服务的实现类中声明AddOnDemand属性为true就可以了。eg:

            [Service(typeof(***), AddOnDemand = true)]
          
            3.至此,Service部分已经实现好了。当在某个View中需要调用一个服务的时候,需要在View的类中加上下面的代码,使View与
            服务联系起来。
            private IGPSService gpsService;
          [ServiceDependency]
    //tell CAB that this class has a dependency on IGPSService
    //you have not initialized a new service, you want to use a service that
    //has already created and stored.
           public IGPSService GPS
          {
               set { gpsService = value; }
           }
          上面的代码告诉CAB,这个类依赖于IGPSService,你想用一个已经被创建的服务,而不是一个新服务。 CAB就用[ServiceDependency] 来实现这个目的。只要在属性前加上这个,就会在一个View添加到WorkItem时自动初始化这个服务。
    要在View中使用这个服务,就要添加这个依赖。
         
          4. 在View中调用服务。比如现在要使用服务中的GeLatitude方法。那么只需要
            gpsService.GetLatitude()就可以了。

          这样就基本完成了服务的设计和与view的连接。还有一些与WorkItem的联系,在具体应用中在做考虑。

  • 相关阅读:
    java忽略安全警告注解@SuppressWarnings
    spring data jpa 报for input String "id"错误解决
    spring Data Jpa 报错 failed to lazily initialize a collection of role: com.itheim.pojo.Role.users, could not initialize proxy
    记一次Content type 'application/json;charset=UTF-8' not supported解决方案
    包冲突异常 loader constraint violation: when resolving interface method "javax.servlet.jsp.JspApplicationContext.getExpressionFacto
    Java运算符(&)、(|)、(^)、(~)
    Java中的原码、补码、反码
    vim编辑器
    Linux yum、tar、rpm、zip、gzip命令的使用
    error Couldn't find a package.json file in
  • 原文地址:https://www.cnblogs.com/lglruirui/p/1780299.html
Copyright © 2020-2023  润新知