首页 > 代码库 > 设计模式之工厂模式

设计模式之工厂模式

定义: 定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

好处: 良好的封装性,调用一个产品只需要知道产品的类名即可。再次,屏蔽产品类,例如在从Mysql切换到Oracle的时候,只需要切换一下驱动名称即可。

package nyx.learn.factory;

public abstract class AbstractFactory {
    public abstract <T extends IHuman> T createHuman(Class<T> c);
}
package nyx.learn.factory;

public class HumanFactory extends AbstractFactory{

    @Override
    public <T extends IHuman> T createHuman(Class<T> c) {
        IHuman human = null;
        try {
            System.out.println(c.getName());
            human = (IHuman)Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return (T)human;
    }
    
}
package nyx.learn.factory;

public interface IHuman {
    void getColor();
    void talk();
}
package nyx.learn.factory;

public class BlackHuman implements IHuman {

    @Override
    public void getColor() {
        System.out.println("黑色皮肤!");
    }

    @Override
    public void talk() {
        System.out.println("说黑话!");
    }

}
package nyx.test.factory;

import nyx.learn.factory.AbstractFactory;
import nyx.learn.factory.BlackHuman;
import nyx.learn.factory.HumanFactory;

public class Main {
    public static void main(String[] args) {
        AbstractFactory factory = new HumanFactory();
        BlackHuman human = factory.createHuman(BlackHuman.class);
        human.getColor();
        human.talk();
    }
}

 

 

工厂模式的扩展:

1、缩小为简单工厂 SimpleFactory

package nyx.learn.factory;

public class SimpleFactory {
    public static <T extends IHuman> T createHuman(Class<T> c){
        IHuman human = null;
        try {
            human = (IHuman)Class.forName(c.getName()).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return (T)human;
    }
}
package nyx.test.factory;

import nyx.learn.factory.BlackHuman;
import nyx.learn.factory.IHuman;
import nyx.learn.factory.SimpleFactory;

public class Main {
    public static void main(String[] args) {
        IHuman human = SimpleFactory.createHuman(BlackHuman.class);
        human.getColor();
        human.talk();
    }
}

简单工厂就是在工厂模式的基础上,去掉继承的抽象类,将方法改成static关键字。可以不需要new 一个工厂,直接调用工厂,产生产品类,简化模式。

 

设计模式之工厂模式