标签:style blog class code java ext
MakeCar.java
package edu.hhxy; /* * 组装车 */ public abstract class MakeCar { //组装车头 public abstract void makeHead(); //组装车身 public abstract void makeBody(); //组装车尾 public abstract void makeTail(); public void make() { this.makeHead(); this.makeBody(); this.makeTail(); } }
MakeBus.java
package edu.hhxy; public class MakeBus extends MakeCar { public void makeBody() { System.out.println("bus:组装车身"); } public void makeHead() { System.out.println("bus:组装车头"); } public void makeTail() { System.out.println("bus:组装车尾"); } }
MakeJeep.java
package edu.hhxy; public class MakeJeep extends MakeCar { public void makeBody() { System.out.println("jeep:组装车身"); } public void makeHead() { System.out.println("jeep:组装车头"); } public void makeTail() { System.out.println("jeep:组装车尾"); } }
MakeKa.java
package edu.hhxy; public class MakeKa extends MakeCar { public void makeBody() { System.out.println("ka:组装车身"); } public void makeHead() { System.out.println("ka:组装车头"); } public void makeTail() { System.out.println("ka:组装车尾"); } }
MainClass.java
package edu.hhxy; public class MainClass { public static void main(String[] args) { MakeCar bus = new MakeBus(); // bus.makeHead(); // bus.makeBody(); // bus.makeTail(); bus.make(); System.out.println("-------------------"); MakeCar jeep = new MakeJeep(); // jeep.makeHead(); // jeep.makeBody(); // jeep.makeTail(); jeep.make(); System.out.println("-------------------"); MakeCar ka = new MakeKa(); ka.make(); } }
以下采用Spring配置方式
applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="makeBus" class="edu.hhxy.MakeBus" /> <bean id="makeJeep" class="edu.hhxy.MakeJeep" /> <bean id="makeKa" class="edu.hhxy.MakeKa" /> </beans>
采用junit进行测试(MakeCarClassTest)(通过接口接收getBean,接收的bean可以是接口的实现类,需要哪个实现类,就get哪个实现类,低耦合)
package edu.hhxy; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MakeCarClassTest { @Test public void getCar() { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); MakeCar makeCar = (MakeCar) ctx.getBean("makeBus"); System.out.println(makeCar); } }
templateMethod(模板方法模式),布布扣,bubuko.com
标签:style blog class code java ext
原文地址:http://www.cnblogs.com/jianfengyun/p/3720749.html