分类: Java
2009-03-31 16:04:15
public interface IMusicBox {
public void play();
}
public class PianoBox implements IMusicBox {
public void play() {
System.out.println("拨放钢琴音乐:)");
}
}
public class ViolinBox implements IMusicBox {
public void play() {
System.out.println("拨放小提琴音乐^_^");
}
}
public class MusicBoxFactory {
public static IMusicBox createMusicBox(String name)
throws InstantiationException,
IllegalAccessException,
ClassNotFoundException {
// 这边使用的是Java的Reflection机制来产生实例
// 不过客户端不用管啦
// 以后就算改变了这边的程式,客户端程式是不用更改的
return (IMusicBox) Class.forName(name).newInstance();
}
}
public class MusicBoxDemo {
public static void main(String[] args) throws Exception {
playMusicBox(MusicBoxFactory.createMusicBox("PianoBox"));
playMusicBox(MusicBoxFactory.createMusicBox("ViolinBox"));
}
public static void playMusicBox(IMusicBox musicBox) {
musicBox.play();
}
}