1. 程式人生 > >Spring 的依賴注入應用代替工廠模式

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