Monday, February 8, 2010

Spring IOC Example - Calculator



Project: Spring_Calculator
Description: This Example shows how three binary operations (Add, Minus, Multiply) can be realized without controller's knowledge. The result can be written to a file or be displayed on the screen.
IDE: Eclipse
JARS:
cglib-nodep-2.1.3.jar
commons-logging-1.1.1.jar
spring.jar (2.5.6)

XML Configuration Diagram

XML Configuration
<bean id="screen" class="com.somellc.spring_calculator.ScreenWriter" /> <bean id="File" class="com.somellc.spring_calculator.DataFileWriter" /> <bean id="multiply" class="com.somellc.spring_calculator.OpMultiply" /> <bean id="add" class="com.somellc.spring_calculator.OpAdd" /> <bean id="minus" class="com.somellc.spring_calculator.OpMinus" />
<bean id="opsbean1" class="com.somellc.spring_calculator.CalculateSpring"> <property name="ops" ref="add" /> <property name="writer" ref="screen"/> </bean>
<bean id="opsbean2" class="com.somellc.spring_calculator.CalculateSpring"> <property name="ops" ref="multiply" /> <property name="writer" ref="screen"/> </bean>
<bean id="opsbean3" class="com.somellc.spring_calculator.CalculateSpring"> <property name="ops" ref="minus" /> <property name="writer" ref="screen"/> </bean>

Operation.java Interface;
public interface Operation {
long operate(long op1, long op2);
String getOpsName();
}

OpAdd.java
public class OpAdd implements Operation{
public OpAdd() {}
public String getOpsName() {
return " plus ";
}
public long operate(long op1, long op2) {
return op1 + op2;
}
}

OpMinus.java
public class OpMinus implements Operation{
public OpMinus() {}
public String getOpsName() {
return " minus ";
}
public long operate(long op1, long op2) {
return op1 - op2;
}
}

OpMultiply.java
public class OpMultiply implements Operation {
public OpMultiply() {}
public String getOpsName() {
return " times ";
}
public long operate(long op1, long op2) {
return op1 * op2;
}
}

ResultWriter.java Interface
public interface ResultWriter {
void showResult(String result) ;
}

ScreenWriter.java
public class ScreenWriter implements ResultWriter{
public ScreenWriter() {}
public void showResult(String result) {
System.out.println(result);
}
}

DataFileWriter.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class DataFileWriter implements ResultWriter {
public DataFileWriter() {}
public void showResult(String result) {
File file = new File("output.txt");
try {
PrintWriter fwriter = new PrintWriter(
new BufferedWriter(new FileWriter(file)));
fwriter.println(result);
fwriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

No comments:

Post a Comment