这是我看了别人写的之后自己为了加强记忆写的,纯属抄袭
先定义一个接口human,
- public interface human{
- void eat();
- void walk();
- }
然后写出实现这个接口的两个子类Chinese和American类
- public class Chinese implements Human{
- public void eat(){
- System.out.println("中国人对吃很有研究");
- }
- public void walk(){
- System.out.println("中国人田径运动不是很强");
- }
- }
- public class American implements Human{
- public void eat(){
- System.out.println("美国人以吃面包为主");
- }
- public void walk(){
- System.out.println("美国的田径运动比较厉害");
- }
- }
然后创建一个工厂类factory,以实现工厂模式
- public class factory{
- public Human getHuman(String name){
- if(name.equalsIgnoreCase(chinese))
- return new Chinese();
- else if(name.equalsIgnoreCase(American)
- return new American();
- else
- throw IllegalArgumentException("你输入的人种错误,不能创建该对象");
- }
- }
下面是一个测试程序,使用工厂方法创建对象
- import java.util.Scanner;
- public class ClientTest{
- public static void main(String[] args){
- System.out.println("input the name of you want to create:");
- Scanner s=new Scanner(System.in);
- String name=s.nextline();
- Human human=null;
- human=new factory().getHuman(name);
- human.eat();
- human.walk();
- }
- }
这就是java的工厂模式
下面介绍一下java spring的IoC(控制翻转inversion of control)模式
在项目根目录下创建一个beam.xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
- <bean id="Chinese" class="cn.com.chengang.spring.Chinese"/>
- <bean id="American" class="cn.com.chengang.spring.American"/>
- </beans>
然后修改ClientTest代码如下:
- import org.springframework.context.support.FileSystemXmlApplicationContext;
- public class ClientTest {
- public static void main(String[] args) {
- ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
- System.out.println("...");
- Scanner s=new Scanner(System.in);
- String name=s.nextline();
- Human human=null;
- human=(Human)ctx.getBean(name);
- human.eat();
- human.walk();
- }
- }
从这个程序可以看到,ctx就相当于原来的Factory工厂,原来的Factory就可以删除掉了。然后又把Factory里的变量移到了ClientTest类里,整个程序结构基本一样。
也许有人说,IoC和工厂模式不是一样的作用吗,用IoC好象还麻烦一点。
举个例子,如果用户需求发生变化,要把Chinese类修改一下。那么前一种工厂模式,就要更改Factory类的方法,并且重新编译布署。而IoC只需要将class属性改变一下,并且由于IoC利用了Java反射机制,这些对象是动态生成的,这时我们就可以热插拨Chinese对象
关于IoC的低侵入性。
什么是低侵入性?如果你用过Struts或EJB就会发现,要继承一些接口或类,才能利用它们的框架开发。这样,系统就被绑定在Struts、EJB上了,对系统的可移植性产生不利的影响。如果代码中很少涉及某一个框架的代码,那么这个框架就可以称做是一个低侵入性的框架。
Spring的侵入性很低,Humen.java、Chinese.java等几个类都不必继承什么接口或类。但在ClientTest里还是有一些Spring的影子:FileSystemXmlApplicationContext类和ctx.getBean方式等。
现在,低侵入性似乎也成了判定一个框架的实现技术好坏的标准之一