| | | 爪哇语言简单工厂创立性模式介绍 | | 2001-11-14·
·阎宏··yesky
| 上一页 1 2 3 4 5 6 7 8 下一页
package com.javapatterns.simplefactory;
public class FruitGardener { public FruitIF factory(String which) throws BadFruitException { if (which.equalsIgnoreCase("apple")) { return new Apple(); } else if (which.equalsIgnoreCase("strawberry")) { return new Strawberry(); } else if (which.equalsIgnoreCase("grape")) { return new Grape(); } else { throw new BadFruitException("Bad fruit request"); } } } | 代码清单5. FruitGardener类的源代码。
package com.javapatterns.simplefactory;
public class BadFruitException extends Exception { public BadFruitException(String msg) { super(msg); } } | 代码清单6. BadFruitException类的源代码。
在使用时,只须呼叫FruitGardener的factory()方法即可
try { FruitGardener gardener = new FruitGardener();
gardener.factory("grape"); gardener.factory("apple"); gardener.factory("strawberry"); ... } catch(BadFruitException e) { ... } | 就这样你的小果园一定会有百果丰收啦!
上一页 1 2 3 4 5 6 7 8 下一页 | | | 感谢
访问天极网,如果您觉得该文章涉及版权问题,请看这里!
|
|