1.// 产品接口
2.public interface Product {
3.
4. public void getName();
5.
6.}
7.
8.// 具体产品A
9.public class ProductA implements Product {
10.
11. public void getName() {
12. System.out.println(" I am ProductA ");
13. }
14.
15.}
16.
17.// 具体产品B
18.public class ProductB implements Product {
19.
20. public void getName() {
21. System.out.println(" I am ProductB ");
22. }
23.
24.}
25.
26.// 工厂类
27.public class ProductCreator {
28.
29. public Product createProduct(String type) {
30. if (" A ".equals(type)) {
31. return new ProductA();
32. }
33. if (" B ".equals(type)) {
34. return new ProductB();
35. } else
36. return null;
37. }
38.
39. public static void main(String[] args) {
40. ProductCreator creator = new ProductCreator();
41. creator.createProduct(" A ").getName();
42. creator.createProduct(" B ").getName();
43. }
44.}