工厂模式

  工厂模式是我们最常用的实例化对象模式了,是用工厂方法代替new操作的一种模式。因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a=new A() 工厂模式也是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑使用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。

  工厂模式有两种形式:工厂方法和抽象工厂。它们的意图是一样的:提供一个接口,在不指定具体类的情况下,创建相关或者依赖的对象。

使用普通代码实现工厂模式

 1 package com;
 2 interface Fruit {
 3     public abstract void eat();
 4 }
 5 class Apple implements Fruit {
 6     public void eat() {
 7         System.out.println("吃苹果");
 8     }
 9 }
10 class Orange implements Fruit {
11     public void eat() {
12         System.out.println("吃橘子");
13     }
14 }
15 class Factory {
16     //根据水果的名字,得到对应的水果
17     public static Fruit getInstance(String fruitName) {
18         Fruit f = null;
19         if("Apple".equals(fruitName)){
20             f = new Apple();
21         }else if("Orange".equals(fruitName)){
22             f = new Orange();
23         }
24         return f;
25     }
26 }
27 public class Test {    
28     public static void main(String[] args){
29         Fruit f = Factory.getInstance("Apple");
30         f.eat();
31         f = Factory.getInstance("Orange");
32         f.eat();
33     }
34 }

将反射机制应用于工厂模式

 1 package com;
 2 interface Fruit {
 3     public abstract void eat();
 4 }
 5 class Apple implements Fruit {
 6     public void eat() {
 7         System.out.println("吃苹果");
 8     }
 9 }
10 class Orange implements Fruit {
11     public void eat() {
12         System.out.println("吃橘子");
13     }
14 }
15 class Factory {
16     //参数为包名+类名,根据这个路径可以获取到对应的类
17     public static Fruit getInstance(String ClassName) {
18         Fruit f = null;
19         try {
20             f = (Fruit) Class.forName(ClassName).newInstance();
21         } catch (Exception e) {
22             e.printStackTrace();
23         }
24         return f;
25     }
26 }
27 public class Test {    
28     public static void main(String[] args){
29         Fruit f = Factory.getInstance("com.Apple");
30         f.eat();
31         f = Factory.getInstance("com.Orange");
32         f.eat();
33     }
34 }
原文地址:https://www.cnblogs.com/acm-bingzi/p/factory.html