To solve out the coupling problems like-difficult to test,difficult to reuse and understand decoupling is used with interface.Lets take a example tour to understand.
directory structure of project-
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="triangle" class="com.test.Triangle"/>
<bean id="ract" class="com.test.Rectangle"/>
</beans>
Output is-
directory structure of project-
Interface HelloApp.java
package com.test;
public interface HelloApp {
public void draw();
}
class Triangle.javapublic interface HelloApp {
public void draw();
}
package com.test;
public class Triangle implements HelloApp {
public void draw()
{
System.out.println("Hello Triangle");
}
}
class Rectangle.javapublic class Triangle implements HelloApp {
public void draw()
{
System.out.println("Hello Triangle");
}
}
package com.test;
public class Rectangle implements HelloApp {
public void draw() {
System.out.println("Hello Ractangle");
}
}
class DrawApp.java(Main class)public class Rectangle implements HelloApp {
public void draw() {
System.out.println("Hello Ractangle");
}
}
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawApp {
public static void main(String a[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
HelloApp tri=(HelloApp) context.getBean("triangle");
tri.draw();
tri=(HelloApp) context.getBean("ract");
tri.draw();
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawApp {
public static void main(String a[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
HelloApp tri=(HelloApp) context.getBean("triangle");
tri.draw();
tri=(HelloApp) context.getBean("ract");
tri.draw();
}
}
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="triangle" class="com.test.Triangle"/>
<bean id="ract" class="com.test.Rectangle"/>
</beans>
Output is-
Hello Triangle
Hello Rectangle
Hello Rectangle
For Further Reading,
0 comments:
Post a Comment