工厂模式【构建模式】

工厂模式

Define an interface for creating object, but let subclass decide which to instantiate.
Factory method lets a class defer instantiation to subclass.
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使得一个类的实例化延迟到子类。

反射工厂

@Slf4j
public class ReflectFactory {
    /**
     *  简单的反射工厂类
     *
     * created by ZXD at 23 Dec 2018 T 11:03:42
     * @param clz
     * @return
     */
    public static final <T> T create(Class<T> clz) {
        try {
            return clz.getDeclaredConstructor().newInstance();
        } catch (final Exception e) {
            log.error(clz.getName(), e);
            return null;
        }
    }
}

实例工厂

  • 将具体工厂类根据产品细化
public class InstanceFactory {

    @Test
    public void all() {
        FruitFactory factory = new AppleFactory();
        Fruit fruit = factory.create();
        assertEquals("apple", fruit.name());

        factory = new BananaFactory();
        fruit = factory.create();
        assertEquals("banana", fruit.name());

        factory = new PearFactory();
        fruit = factory.create();
        assertEquals("pear", fruit.name());
    }
}

// 1)抽象产品类:定义产品的共性
interface Fruit {
    String name();
}

// 2)工厂接口
interface FruitFactory {
    Fruit create();
}

// 3)具体产品类:定义产品的特性
class Apple implements Fruit {
    @Override
    public String name() {
        return "apple";
    }
}

class Banana implements Fruit {
    @Override
    public String name() {
        return "banana";
    }
}

class Pear implements Fruit {
    @Override
    public String name() {
        return "pear";
    }
}

// 4)具体的实例工厂类
class AppleFactory implements FruitFactory {
    @Override
    public Apple create() {
        return new Apple();
    }
}

class BananaFactory implements FruitFactory {
    @Override
    public Banana create() {
        return new Banana();
    }
}

class PearFactory implements FruitFactory {
    @Override
    public Pear create() {
        return new Pear();
    }
}

posted on 2018-12-23 11:08  竺旭东  阅读(76)  评论(0编辑  收藏  举报

导航