zoukankan      html  css  js  c++  java
  • 反射实现接口工厂

    接口工厂模式:

          定义接口用Interface,且接口中只能包含属性、方法和索引器,而且成员上不能有任何修饰符即使是public也不行,因为接口总是公开的。

         首先我们定义一个汽车接口

         public interface ICar
         {
             void run();
             void stop();
             //void error();
         }

         这里我们再定义一个Jeep车类和宝马车类都继承汽车接口,实现接口

         public class Jeep:ICar

         {

              public void run()
              {
           HttpContext.Current.Response.Write("Jeep run<br/>");
         }
          public void stop()
          {
              HttpContext.Current.Response.Write("Jeep stop<br/>");
          }          

          }

       public class Bmw:ICar

       {

              public void run()
              {
          HttpContext.Current.Response.Write("Bmw run<br/>");
         }
          public void stop()
          {
              HttpContext.Current.Response.Write("JBmw stop<br/>");
          }       

        }

       接下来就是关键的工厂了,我们只需要知道传变量到工厂里面,不管它是怎么实现的

    public class TcFactory
    {
        public TcFactory()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //       
        }
        public static ICar GetCarInstance(string className)
        {
            ICar car = null;
            Type type = Type.GetType(className); //获得指定名称的类
            car = (ICar)Activator.CreateInstance(type); //创建类型
            return car;
        }
    }

         是不是很方面,无需在工厂里面进行一一定义Jeep和Bmw了,工厂会自动创建你想要的类并返回

        调用工厂

        ICar car = TcFactory.GetCarInstance("Jeep");
            car.run();
            car.stop();

       但是想想还是不太完善,假如要加一个故障方法error(),那么接口里面要加,而且继承接口的类也都要加起不繁琐,这样我们就用abstract抽象工厂  下篇。。。

  • 相关阅读:
    Git 远程仓库 git remote
    同一台电脑关于多个SSH KEY管理
    dotnet core on Linux 环境搭建及入门demo
    Cannot load JDBC driver class 'com.mysql.jdbc.Driver '
    Mac OS 配置Maven
    Linux中profile、bashrc、bash_profile之间的区别和联系
    如何在Mac的Finder中显示/usr、/tmp、/var等隐藏目录
    Mac OS X 下查看和设置JAVA_HOME
    SSM框架整合(IntelliJ IDEA + maven + Spring + SpringMVC + MyBatis)
    事件
  • 原文地址:https://www.cnblogs.com/ajun/p/2815919.html
Copyright © 2011-2022 走看看