ITPub博客

首页 > IT职业 > IT图书 > 行为的抽象即是接口(Interface)

行为的抽象即是接口(Interface)

IT图书 作者:kalt 时间:2021-09-09 09:46:37 0 删除 编辑

行为抽象即可写成接口(Interface)。
如此http://www.cnblogs.com/insus/archive/2013/02/24/2924190.html链接的例子中的开与关,就可以把它们设计为抽象方法。
我们宣告接口时,使用interface来声明,就如宣告类使用class一样。在编程规范中,使用字母"I"开头。接口中的所有签名,如方法,属性,索引器,事件等。不能带修饰符,比如public,private等,不能有任何实现内容,也不能声明虚拟(virtual)的或静态(static)的等。

ISwitchable

using System;using System.Collections.Generic;using System.Linq;using System.Web;/// /// Summary description for ISwitchable/// namespace Insus.NET{    public interface ISwitchable    {        void TurnOn();        void TurnOff();    }}


Insus.NET在此列举几个方面,如果生活中,我们需要开关水龙头,门与窗户,手机关机更换电池或打开使用等等。这样,统一接口,在开发过程中可以做到规范程序。

比如白炽灯,实现接口:

IncandescentLamp

using System;using System.Collections.Generic;using System.Linq;using System.Web;/// /// Summary description for IncandescentLamp/// namespace Insus.NET{    public class IncandescentLamp : ISwitchable    {        public IncandescentLamp()        {            //            // TODO: Add constructor logic here            //        }        public void TurnOn()        {            HttpContext.Current.Response.Clear();            string On_Light = "";            HttpContext.Current.Response.Write(On_Light);        }        public void TurnOff()        {            HttpContext.Current.Response.Clear();            string Off_Light = "";            HttpContext.Current.Response.Write(Off_Light);        }    }}


水龙头实现接口:

WaterTap

using System;using System.Collections.Generic;using System.Linq;using System.Web;/// /// Summary description for WaterTap/// namespace Insus.NET{    public class WaterTap : ISwitchable    {        public WaterTap()        {            //            // TODO: Add constructor logic here            //        }        public void TurnOn()        {            //水龙头打开        }        public void TurnOff()        {            //水龙头关闭        }    }}


门实现接口:

Door

using System;using System.Collections.Generic;using System.Linq;using System.Web;/// /// Summary description for Door/// namespace Insus.NET{    public class Door: ISwitchable    {        public void TurnOn()        {           //写门打开的事情。        }        public void TurnOff()        {          //写门关闭的事情。        }    }}


只要对象的行为有“开”与“关”的,均可以此接口为实现。

Insus.NET在ASP.NET开发过程中,使用过大量的接口,来解决诸多问题:http://www.cnblogs.com/insus/category/308317.html or http://www.cnblogs.com/insus/category/225730.html

 

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1805/viewspace-2812098/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    121
  • 访问量
    892