美文网首页
设计模式学习-工厂方法模式

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

作者: m1Ku | 来源:发表于2018-12-16 11:09 被阅读0次

定义

工厂方法模式是创建性设计模式。定义一个用于创建对象的接口,让子类决定实例化哪个类。复杂对象适合使用工厂模式,用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方法就相当于一个工厂方法,会构造一个具体的迭代器对象返回,也就是做到了让子类决定实例化哪个类。

相关文章

  • 2021-11-16 - 学习记录

    设计模式学习:创建型:工厂(工厂方法,抽象工厂),建造者,单例,原型 设计模式:工厂模式 简单工厂 工厂方法 抽象工厂

  • 设计模式-抽象工厂模式

    前面我们学习了了简单工厂模式和工厂方法模式,今天我们来学习设计模式中最后的一种工厂模式——抽象工厂模式(Abstr...

  • 工厂模式

    工厂模式 就是工厂---生产-->产品 在设计模式中,分为 简单工厂模式, 工厂方法模式,抽象工厂模式. 工厂模式...

  • PHP-浅谈单例模式和工厂模式

    PHP中常用的设计模式有单例模式、工厂模式(简单工厂模式、工厂方法模式和抽象工厂方法模式)、适配模式、策略模式。 ...

  • 设计模式-工厂模式

    设计模式1 设计模式2 工厂模式 工厂模式可简单的分为三类:简单工厂,工厂方法,抽象工厂 简单工厂模式 定义 简单...

  • 设计模式之工厂方法模式(创建型)

    一、模式定义 工厂方法模式:又称工厂模式,也叫虚拟构造器模式,属于构建型设计模式,工厂方法模式是在简单工厂模式上进...

  • spring 设计模式篇(前)

    设计模式俗称:套路 一、spring常见设计模式 (23种设计模式) 创建型:工厂方法模式、抽象工厂模式、建造者...

  • 设计模式系列-简单工厂模式

    JAVA设计模式系列: 单例模式 观察者模式 模板方法模式 简单工厂模式 定义 简单工厂模式又叫做静态工厂方法模式...

  • 简单工厂模式

    Android进阶之设计模式 简单工厂模式 简单工厂模式(又叫作静态工厂方法模式), 其属于创建型设计模式,但并不...

  • 设计模式之简单工厂、工厂方法、抽象工厂

    设计模式之简单工厂、工厂方法、抽象工厂 什么是设计模式? 设计模式(Design pattern)代表了最佳的实践...

网友评论

      本文标题:设计模式学习-工厂方法模式

      本文链接:https://www.haomeiwen.com/subject/bubtkqtx.html