01简单工厂模式SimpleFactory

一、什么是简单工厂模式

  简单工厂模式属于类的创建型模式,又叫做静态 工厂方法模式。通过专门定义一个类来负责创建 其他类的实例,被创建的实例通常都具有共同的 父类。

二、模式中包含的角色及其职责

1.工厂(Creator)

  角色 简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类可以被外界直接调用,创建所需的产品对象。

2.抽象(Product)角色

  简单工厂模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。

3.具体产品(Concrete Product)

  角色 简单工厂模式所创建的具体实例对象

三、简单工厂模式的优缺点

  在这个模式中,工厂类是整个模式的关键所在。它包含必要的判断 逻辑,能够根据外界给定的信息,决定究竟应该创建哪个具体类的 对象。用户在使用时可以直接根据工厂类去创建所需的实例,而无 需了解这些对象是如何创建以及如何组织的。有利于整个软件体系 结构的优化。

  不难发现,简单工厂模式的缺点也正体现在其工厂类上,由于工厂类集中 了所有实例的创建逻辑,所以“高内聚”方面做的并不好。另外,当系统中的 具体产品类不断增多时,可能会出现要求工厂类也要做相应的修改,扩展 性并不很好。

苹果类

1 public class Apple implements Fruit{
2     /*
3      * 采集
4      */
5     public void get(){
6         System.out.println("采集苹果");
7     }
8 }

香蕉类

1 public class Banana implements Fruit{
2     /*
3      * 采集
4      */
5     public void get(){
6         System.out.println("采集香蕉");
7     }
8 }

水果类

1 public interface Fruit {
2     /*
3      * 采集
4      */
5     public void get();
6 }

水果工厂

 1 public class FruitFactory {
 2 //    /*
 3 //     * 获得Apple类的实例
 4 //     */
 5 //    public static  Fruit getApple() {
 6 //        return new Apple();
 7 //    }
 8 //    
 9 //    /*
10 //     * 获得Banana类实例
11 //     */
12 //    public static Fruit getBanana() {
13 //        return new Banana();
14 //    }
15     /*
16      * get方法,获得所有产品对象
17      */
18     public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
19 //        if(type.equalsIgnoreCase("apple")) {
20 //            return Apple.class.newInstance();
21 //            
22 //        } else if(type.equalsIgnoreCase("banana")) {
23 //            return Banana.class.newInstance();
24 //        } else {
25 //            System.out.println("找不到相应的实例化类");
26 //            return null;
27 //        }
28             Class fruit = Class.forName(type);
29             return (Fruit) fruit.newInstance();
30     }
31 }

测试方法

 1 public class MainClass {
 2     public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
 3 //        //实例化一个Apple
 4 //        Apple apple = new Apple();
 5 //        //实例化一个Banana
 6 //        Banana banana = new Banana();
 7 //        
 8 //        apple.get();
 9 //        banana.get();
10         
11 //        //实例化一个Apple,用到了多态
12 //        Fruit apple = new Apple();
13 //        Fruit banana = new Banana();
14 //        apple.get();
15 //        banana.get();
16         
17 //        //实例化一个Apple
18 //        Fruit apple = FruitFactory.getApple();
19 //        Fruit banana = FruitFactory.getBanana();
20 //        apple.get();
21 //        banana.get();
22         
23         Fruit apple = FruitFactory.getFruit("Apple");
24         Fruit banana = FruitFactory.getFruit("Banana");
25         apple.get();
26         banana.get();
27     }
28 }

猜你喜欢

转载自www.cnblogs.com/justdoitba/p/9031272.html