标签:equal interface getbean code div course 修改 nts java
原始方法:
main函数:
public static void learnCourse(){ student student=new student(); student.learnJava(); student.learnHtml(); } public static void main(String[] args){ learnCourse(); }
student类中加入:
public void learnJava(){ Icourse course=new JavaIcourse(); course.learn(); } public void learnHtml(){ Icourse course=new HtmlIcourse(); course.learn(); }
使用接口Icourse 用类JavaIcourse和HtmlIcourse进行继承,并重写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"); } }
使用工厂模式:
改变的地方:
main函数:
public static void learnCourse(){ student student=new student(); student.learn("java"); } public static void main(String[] args){ learnCourse(); }
student类中:
public void learn(String name){ Icourse course=factory.getCourse(name); course.learn(); }
加入factory类(工厂模式):
public class factory { //根据名字获取课程的方法 public static Icourse getCourse(String name){ if(name.equals("java")){ return new JavaIcourse(); } else return new HtmlIcourse(); } }
将factory类去掉在bean中添加:
<bean id="JavaIcourse" class="org_shitang_instance.JavaIcourse"></bean> <bean id="HtmlIcourse" class="org_shitang_instance.HtmlIcourse"></bean>
在student类中修改:
public void learn(String name){ ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml"); Icourse course=(Icourse)conext.getBean(name); course.learn(); }
main函数中:
public static void main(String[] args){ ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml"); student student=(student)conext.getBean("student"); student.learn("Html"); }
标签:equal interface getbean code div course 修改 nts java
原文地址:https://www.cnblogs.com/lmff/p/12748663.html