接口--工厂设计模式

左手的ㄟ右手 2022-06-10 12:38 278阅读 0赞
  1. interface Fruit{ //定义一个接口
  2. public void eat();
  3. }
  4. class Apple implements Fruit{ //实现接口
  5. public void eat() {
  6. System.out.println("吃苹果");
  7. }
  8. }
  9. class Orange implements Fruit{ //实现接口
  10. public void eat() {
  11. System.out.println("吃橘子");
  12. }
  13. }
  14. class Factory{
  15. public static Fruit getInstance(String className) {
  16. if("apple".equals(className)) {
  17. return new Apple();
  18. }
  19. if("orange".equals(className)) {
  20. return new Orange();
  21. }
  22. return null;
  23. }
  24. }
  25. public class Test {
  26. public static void main(String[] args) {
  27. Fruit f = Factory.getInstance("apple");
  28. f.eat();
  29. }
  30. }

输出结果:
吃苹果

发表评论

表情:
评论列表 (有 0 条评论,278人围观)

还没有评论,来说两句吧...

相关阅读