设计模式学习-工厂方法模式

定义

工厂方法模式是创建性设计模式。定义一个用于创建对象的接口,让子类决定实例化哪个类。复杂对象适合使用工厂模式,用new就可以完成创建的对象无需使用工厂模式。

UML类图

工厂方法模式

工厂方法模式的角色

  • Product

    抽象产品类,工厂方法模式创建的产品的父类

  • ConcreteProduct

    具体的产品类,实现具体的产品的业务逻辑

  • Factory

    抽象工厂类,定义了构建产品的方法

  • ConcreteFactory

    具体工厂类,实现了构建产品的具体业务

示例

我们平时穿的Adidas鞋子有很多型号,比如PureBoost、UltraBoost等,但是这些鞋子都是由Adidas工厂生产的。

工厂方法模式

/**
 * 抽象产品类
 * 阿迪达斯鞋
 */
public abstract class AdidasShoes {
    public abstract void run();
}

/**
 * 具体产品类
 * PureBoost鞋
 */
public class PureBoost extends AdidasShoes {
    @Override
    public void run() {
        System.out.println("PureBoost run!");
    }
}

/**
 * 具体产品类
 * UltraBoost鞋
 */
public class UltraBoost extends AdidasShoes {
    @Override
    public void run() {
        System.out.println("UltraBoost run!");
    }
}

/**
 * 抽象工厂类
 * 定义创建产品类的方法
 */
public abstract  class Factory {
    public abstract  <T extends AdidasShoes>  T createShoes(Class<T> tClass);
}

/**
 * 具体工厂类
 * 实现创建具体产品类的方法
 * 可以传入产品子类class对象,通过反射创建具体的产品类
 */
public class AdidasFactory extends Factory {
    @Override
    public <T extends AdidasShoes> T createShoes(Class<T> tClass) {
        AdidasShoes shoes = null;
        try {
            shoes = (AdidasShoes) Class.forName(tClass.getName()).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) shoes;
    }
}

public static void main(String[] args) {
      Factory factory = new AdidasFactory();
      PureBoost pureBoost = factory.createShoes(PureBoost.class);
      pureBoost.run();

      UltraBoost ultraBoost = factory.createShoes(UltraBoost.class);
      ultraBoost.run();
 }

PureBoost run!
UltraBoost run!

如上面的工厂方法模式,我们也可以为每一种型号的鞋定义一个具体的工厂,这种有多个工厂的方式叫多工厂方法模式。

简单工厂模式

当工厂只有一个时,我们可以省略抽象工厂,此时只需要将工厂方法改为静态方法即可,这种方式又叫静态工厂模式。

/**
 * 简单工厂模式
 * 工厂方法为静态方法
 */
public class SimpleFactory {
    public static AdidasShoes createPureBoost (){
        return new PureBoost();
    }
}

Android源码中的工厂方法模式

开发中常用的ArrayList就有工厂模式的应用。ArrayList实现了List接口,List接口继承自Collection接口,Collection接口继承自Iterable接口,Iterable接口中有一个iterator方法返回Iterator实例

public interface Iterable<T> {
    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();
    //...
}

ArrayList实现了这个方法,构造并返回了一个迭代器对象。

public Iterator<E> iterator() {
    return new Itr();
}

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    Itr() {}

    public boolean hasNext() {
        return cursor != size;
    }

    @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];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

那么实现了Iterable接口的类,例如LinkedList、HashSet等,也会实现了iterator方法并且构造具体的迭代器对象。这里的iterator方法就相当于一个工厂方法,会构造一个具体的迭代器对象返回,也就是做到了让子类决定实例化哪个类。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容