简单工厂模式属于创建型模式,又叫静态工厂方法模式。通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
该模式主要包含的角色有:工厂角色,抽象角色,具体产品角色。以下的几个类就是一个简单工厂模式的示例。
1.抽象接口或父类
public interface Fruit {
/*
* 获取方法
*/
public void get();
}
2. 具体实现类
具体实现类1:
public class Apple implements Fruit {
@Override
public void get() {
System.out.println("采集小苹果");
}
}
具体实现类2:
public class Banana implements Fruit {
@Override
public void get() {
System.out.println("采集香蕉");
}
}
3. 简单工厂类
public class FruitFactory {
/*
* 简单工厂模式方式一
*/
public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException {
if(type.equalsIgnoreCase("apple")) {
return Apple.class.newInstance();
} else if(type.equalsIgnoreCase("banana")) {
return Banana.class.newInstance();
} else {
System.out.println("没有找到相应的类型");
return null;
}
}
/*
* 简单工厂模式方式二
*/
public static Fruit getFruit2(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
@SuppressWarnings("rawtypes")
Class clazz = Class.forName(type);
return (Fruit) clazz.newInstance();
}
}
使用JUnit测试简单工厂方法类:
public class TestSimpleFactory {
@Test
public void test() throws InstantiationException, IllegalAccessException {
Fruit apple = FruitFactory.getFruit("apple");
Fruit banana = FruitFactory.getFruit("banana");
apple.get();
banana.get();
}
@Test
public void test2() throws InstantiationException, IllegalAccessException {
Fruit apple = FruitFactory.getFruit("Apple");
Fruit banana = FruitFactory.getFruit("Banana");
apple.get();
banana.get();
}
}
以上几个类就显示简单工厂模式的使用方法,总的来说简单工厂方法就是通过一个工厂类根据具体对象类名去获得实例对象。
个人微信公众号:programmlife,如有兴趣敬请关注,主要表达了一个码农的所见所思所叹,也可扫描下方二维码关注: