【设计模式】简单工厂模式和工厂方法模式

简单工厂模式

顾名思义,此模式的设计结构是简单的,核心是生产对象。

一般来说,运用工厂模式生产的对象应该是构建对象的过程比较复杂的,获取构建对象的过程在日后可能发生变更的。

简单工厂模式,在工厂类中直接生产对象,即工厂类中直接依赖对象类。

代码见:

https://github.com/nicchagil/design-pattern-exercise-with-java/tree/master/简单工厂模式

工厂方法模式

使用简单工厂模式,

假如有一天,Factory生产的Dog对象要全部切换为Wolf(狼),那么我们在Factory的产生方法中修改逻辑即可。(此假设场景是全部哦,既然要将产生Dog变更为产生Wolf,那么修改代码逻辑无可厚非)

假如有一天,某些客户端原来使用Cat对象的地方,需要使用Dog对象,这需要在客户端修改代码。(这也不是用工厂方法模式能解决的)

最后,假如有一天,需要添加生产一个Duck(鸭),那么难道要修改Factory?如果我们的生产方法写出如下,那么修改的代码量会更多,而且改起来容易错。

    public static Animal getInstance(String type) {
        if (type == null || type.trim().length() == 0) {
            return null;
        }
        
        if (type.equals("dog")) {
            return new Dog();
        } else if (type.equals("cat")) {
            return new Cat();
        }
        
        return null;
    }
View Code

那么,如果,我们使用工厂方法模式,只需要增加几个类,就可完成增加Duck的类型。

实体类如“简单工厂模式”,省略。

package No002工厂方式模式;

import No002工厂方式模式.model.Animal;

public interface IFactory {
    
    public Animal getInstance();

}
View Code
package No002工厂方式模式;

import No002工厂方式模式.model.Animal;
import No002工厂方式模式.model.Dog;

public class DogFactory implements IFactory {

    public Animal getInstance() {
        return new Dog();
    }

}
View Code
package No002工厂方式模式;

import No002工厂方式模式.model.Animal;
import No002工厂方式模式.model.Cat;

public class CatFactory implements IFactory {

    public Animal getInstance() {
        return new Cat();
    }

}
View Code
package No002工厂方式模式;

public class Call {

    public static void main(String[] args) {
        IFactory f = new DogFactory();
        System.out.println(f.getInstance());
        
        IFactory ff = new CatFactory();
        System.out.println(ff.getInstance());
    }

}
View Code

其类图是这样的:

JDK不乏工厂方法模式的例子,我们熟悉的ArrayList、LinkedList的iterator()就是其一,看看如下类图就知:

Iterable:

Iterator:

简单看下ArrayList.Itr的一个方法的实现:

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
原文地址:https://www.cnblogs.com/nick-huang/p/5048066.html