Spring 的依赖注入应用代替工厂模式

接口


package FactoryExample;

public interface Human {
    void eat();
    void walk();
    void show();
}

实现

实现一


package FactoryExample;

public class Man implements Human {
    @Override
    public void eat() {
        System.out.println("男人吃饭,吃完饭打炮!");
    }

    @Override
    public void walk() {
        System.out.println("男人走路,走完路打不了炮!");
    }

    @Override
    public void show() {
        if (this.equals(null)) {
            System.out.println("空对象");
        } else {
            this.eat();
            this.walk();
        }
    }
}

实现二


package FactoryExample;

public class Women implements Human {
    @Override
    public void eat() {
        System.out.println("女人吃饭!吃完饭被干!");
    }

    @Override
    public void walk() {
        System.out.println("女人走路,和男人一样!");
    }

    @Override
    public void show() {
        if (this.equals(null)) {
            System.out.println("空对象");
        } else {
            this.eat();
            this.walk();
        }
    }
}

srping-config.xml文件配置


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean>
<code>package FactoryExample;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SrpingTest {
    public static void main(String[] args) {
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("src/spring-config.xml");

        Human human = null;

        //返回 Object 类型 , 所以要加上 类型转换
        human = (Human) ctx.getBean("man");

        human.show();

        human = (Human) ctx.getBean("women");

        human.show();

    }
}

就是这样,我的可以使用,我不知道为什么可以使用,但是就是可以使用!

来源:https://blog.csdn.net/lpZhouYi/article/details/85228122

猜你喜欢

转载自www.cnblogs.com/thatme/p/10192990.html