carfield.com.hk
ShapeFactory1.java
2001-12-26T16:00:00Z
2001-12-26T16:00:00Z
<br/><TEXTAREA name="code" class="java" rows="16" cols="100">//: c05:shapefact1:ShapeFactory1.java
// A simple static factory method.
package c05.shapefact1;
import java.util.*;
import com.bruceeckel.test.*;
abstract class Shape {
public abstract void draw();
public abstract void erase();
public static Shape factory(String type) {
if(type.equals("Circle")) return new Circle();
if(type.equals("Square")) return new Square();
throw new RuntimeException(
"Bad shape creation: " + type);
}
}
class Circle extends Shape {
Circle() {} // Friendly constructor
public void draw() {
System.out.println("Circle.draw");
}
public void erase() {
System.out.println("Circle.erase");
}
}
class Square extends Shape {
Square() {} // Friendly constructor
public void draw() {
System.out.println("Square.draw");
}
public void erase() {
System.out.println("Square.erase");
}
}
public class ShapeFactory1 extends UnitTest {
String shlist[] = { "Circle", "Square",
"Square", "Circle", "Circle", "Square" };
List shapes = new ArrayList();
public void test() {
for(int i = 0; i < shlist.length; i++)
shapes.add(Shape.factory(shlist[i]));
Iterator i = shapes.iterator();
while(i.hasNext()) {
Shape s = (Shape)i.next();
s.draw();
s.erase();
}
}
public static void main(String args[]) {
new ShapeFactory1().test();
}
} ///:~
</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
2001-12-26T16:00:00Z
makefile
2001-12-26T16:00:00Z
2001-12-26T16:00:00Z
<br/><TEXTAREA name="code" class="" rows="16" cols="100"># From Thinking in Patterns (with Java) by Bruce Eckel
# At http://www.BruceEckel.com
# (c)2001 Bruce Eckel
# Copyright notice in Copyright.txt
# Automatically-generated MAKEFILE
# For examples in directory .\c05\shapefact1
# using the JDK 1.3 compiler
# Invoke with: make
HOME := ../../
ifndef MAKECMDGOALS
MAKECMDGOALS := javac
endif
# Command.com is too weak to build this under Windows NT/2000:
ifeq ($(OS),Windows_NT)
COMSPEC=$(SYSTEMROOT)\system32\cmd.exe
endif
ifneq ($(MAKECMDGOALS),clean)
include $(HOME)/$(MAKECMDGOALS).mac
endif
.SUFFIXES : .class .java
.java.class :
$(JVC) $(JVCFLAGS) $<
javac: \
ShapeFactory1.class
jikes: \
ShapeFactory1.class
clean:
ifeq ($(notdir $(SHELL)),COMMAND.COM)
del *.class
else
rm -f *.class
endif
ShapeFactory1.class: ShapeFactory1.java
$(JVC) $(JVCFLAGS) $<
java com.bruceeckel.test.RunUnitTests c05.shapefact1.ShapeFactory1
</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
2001-12-26T16:00:00Z