Spring框架中<bean>第一种补充
2021-02-09 22:18
标签:equal interface getbean code div course 修改 nts java 原始方法: main函数: student类中加入: 使用接口Icourse 用类JavaIcourse和HtmlIcourse进行继承,并重写learn函数 使用工厂模式: 改变的地方: main函数: student类中: 加入factory类(工厂模式): 将factory类去掉在bean中添加: 在student类中修改: main函数中: 标签:equal interface getbean code div course 修改 nts java 原文地址:https://www.cnblogs.com/lmff/p/12748663.htmlpublic static void learnCourse(){
student student=new student();
student.learnJava();
student.learnHtml();
}
public static void main(String[] args){
learnCourse();
}
public void learnJava(){
Icourse course=new JavaIcourse();
course.learn();
}
public void learnHtml(){
Icourse course=new HtmlIcourse();
course.learn();
}
Icourse:
public interface Icourse {
void learn();
}
JavaIcourse:
public class JavaIcourse implements Icourse{
public void learn(){
System.out.println("学习java");
}
}
HtmlIcourse:
public class HtmlIcourse implements Icourse{
public void learn(){
System.out.println("学习html");
}
}
public static void learnCourse(){
student student=new student();
student.learn("java");
}
public static void main(String[] args){
learnCourse();
}
public void learn(String name){
Icourse course=factory.getCourse(name);
course.learn();
}
public class factory {
//根据名字获取课程的方法
public static Icourse getCourse(String name){
if(name.equals("java")){
return new JavaIcourse();
}
else
return new HtmlIcourse();
}
}
public void learn(String name){
ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml");
Icourse course=(Icourse)conext.getBean(name);
course.learn();
}
public static void main(String[] args){
ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml");
student student=(student)conext.getBean("student");
student.learn("Html");
}
上一篇:Java反射
文章标题:Spring框架中<bean>第一种补充
文章链接:http://soscw.com/index.php/essay/53290.html