public interface IMusicBox {
public void play();
}
public void play();
}
public class PianoBox implements IMusicBox {
public void play() {
System.out.println("播放钢琴音乐。");
}
}
public void play() {
System.out.println("播放钢琴音乐。");
}
}
public class ViolinBox implements IMusicBox {
public void play() {
System.out.println("播放小提琴音乐。");
}
}
public void play() {
System.out.println("播放小提琴音乐。");
}
}
public class IMusicBoxFactory {
public static IMusicBox createMusicBox(String name) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
//使用的是Java的Reflection机制来产生实例
return (IMusicBox) Class.forName(name).newInstance();
}
}
public static IMusicBox createMusicBox(String name) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
//使用的是Java的Reflection机制来产生实例
return (IMusicBox) Class.forName(name).newInstance();
}
}
TestDemo类:
public static void main(String[] args) {
try {
playMusicBox(IMusicBoxFactory.createMusicBox("com.dpt.factory.sample.PianoBox"));
playMusicBox(IMusicBoxFactory.createMusicBox("com.dpt.factory.sample.ViolinBox"));
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void playMusicBox(IMusicBox imb){
imb.play();
}
try {
playMusicBox(IMusicBoxFactory.createMusicBox("com.dpt.factory.sample.PianoBox"));
playMusicBox(IMusicBoxFactory.createMusicBox("com.dpt.factory.sample.ViolinBox"));
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void playMusicBox(IMusicBox imb){
imb.play();
}
参考地址:
设计模式http://www.riabook.cn/doc/designpattern/