3. public class Square implements Shape { 4.
5. public void draw() {
6. // TODO Auto-generated method stub
7. System.out.println(\8. } 9.
10.public void erase() {
11. // TODO Auto-generated method stub
12. System.out.println(\13.}
14.private static class Factory extends ShapeFactory 15.{
16. protected Shape create() 17. {
18. return new Square(); 19. } 20.}
21.static {ShapeFactory.addFactory(\22. 23.}
24.最后,我们来测试一下:
25.String[] ids = new String[]{\};
26. for(int i=0;i 28. Shape shape = ShapeFactory.createShape(ids[i]); 29. shape.draw(); 30. shape.erase(); 31. } 32.测试结果为: 33.the circle is drawing... 34.the circle is erasing... 35.the square is drawing... 36.the square is erasing... 37.the square is drawing... 38.the square is erasing... 39.the circle is drawing... 40.the circle is erasing... 这个方法是巧妙地使用了内部类,将具体类的实现和它的具体工厂类绑定起来,由具体类的实现者在这个内部类的具体工厂里去产生一个具体类的对 11 象,这当然容易得多。虽然需要每一个具体类都创建一个具体工厂类,但由于具体工厂类是一个内部类,这样也不会随着具体类的增加而不断增加新的工厂类,使得代码看起来很臃肿,这也是本方法不得不使用内部类的一个原因吧。 12 百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库java内部类的四个应用场景(3)在线全文阅读。
相关推荐: