一、先演示 “简单工厂”:

 1 package org;
 2 
 3 interface Fruit {
 4     public void eat();
 5 }
 6 
 7 class Apple implements Fruit {
 8     public void eat() {
 9         System.out.println("吃苹果。");
10     }
11 }
12 
13 class Orange implements Fruit {
14     public void eat() {
15         System.out.println("吃橘子");
16     }
17 }
18 
19 class Factory { // 工厂类
20     public static Fruit getInstance(String className) {
21         Fruit f = null;
22         if (className.equals("apple")) {
23             f = new Apple();
24         }
25         if (className.endsWith("orange")) {
26             f = new Orange();
27         }
28         return f;
29     }
30 }
31 
32 public class FactoryDemo {
33     public static void main(String args[]) {
34         Fruit f = Factory.getInstance("apple");
35         f.eat();
36     }
37 }
View Code

相关文章:

  • 2022-12-23
  • 2021-10-31
  • 2021-07-23
  • 2021-11-16
  • 2021-07-24
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-27
  • 2021-08-24
  • 2022-12-23
  • 2021-09-29
  • 2022-01-05
  • 2022-02-11
相关资源
相似解决方案