从工厂模式到依赖注入的逻辑演变
在介绍工厂模式与控制反转(Inversionof Control)及依赖注入(DependencyInjection)之前,先介绍下类的调用方法。目前调用方法总共有3种:1.自己创建;2.工厂模式;3.外部注入,其中外部注入即为控制反转/依赖注入模式(IoC/DI)。我们可以用3个形象的东西来分别表示它们,就是new、get、set。顾名思义,new表示自己创建,get表示主动去取(即工厂),set表示是被别人送进来的(即注入),其中get和set分别表示了主动去取和等待送来两种截然相反的特性,这3个单词代表了3种方法的思想精髓。 无论是那一种方法,都存在两个角色,那就是调用者和被调用者。下面我们通过实例来讲解这3种方法的具体含义。首先,我们设定调用对象为学生对象Student,被调用者对象为图书对象Book,要设计的代码功能是学生学习图书。我们一般习惯于一种思维编程方式:接口驱动,可以提供不同灵活的子类实现: //Book接口 publicinterface IBook{ public void learn(); } //BookA实现类 publicclass BookA implements IBook { public void learn(){ System.out.println("学习BookA"); } } //BookB实现类 publicclass BookB implements IBook { public void learn(){ System.out.println("学习BookB"); } }
publicclass Student { public void learnBookA(){ IBook book = new BookA(); book.learn(); } public void learnBookB(){ IBook book = new BookB(); book.learn(); } }
//图书工厂 publicclass BookFactory{ public static IBook getBookA() { IBook book = new BookA(); return book; } public static IBook getBookB() { IBook book = new BookB(); return book; } } //学生类 publicclass Student { public void learnBookA(){ IBook book = BookFactory.getBookA(); book.learn(); } public void learnBookB(){ IBook book = BookFactory.getBookB(); book.learn(); } }
publicclass Student{ private IBook bookA; public init(){ bookA =(IBook)Class.forName("BookA").newInstance(); } }
publicclass Student { private BookA bookA; public Student (BookA booA){ this.bookA= bookA; } public void learn() { bookA.learn(); } } publicclass Factory { public static getInstance(){ Classclazz = BookA.class; //创建类BookA的Class对象 Class[]param = new Class[]{BookA.class}; try{ Constructor con = clazz.getConstructor(param); BookA bookA = (BookA)con.newInstance(str); Student student1 = new Student(bookA); }catch(Exception e){ e.printStackTrace(); } returnstudent1; } }
publicclass Student { private BookA bookA; public BookA getBookA(BookA booA){ returnbookA; } public void setBookA(BookA booA){ this.bookA= bookA; } public void learn() { bookA.learn(); } } publicclass Factory { public static getInstance(String fieldName){ Classclazz = BookA.class; //创建类BookA的Class对象 Classstudent = Student.class; Class[]param = new Class[]{BookA.class}; try{ Method method =student.getMethod("set"+change(fieldName),param); BookA bookA = (BookA)clazz.newInstance(); BookA[] book = new BookA[] {bookA}; Object obj = student.newInstance(); method.invoke(obj,book); Student student1 = (Student) obj; }catch(Exception e){ e.printStackTrace(); } returnstudent1; } public static String change(String str) { StringsubString = str.substring(0,1); subString= subString.toUpperCase(); str= str.substring(1,str.length()); str= subString + str; returnstr; } }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |